Compare commits

...
7 Commits
Author SHA1 Message Date
yunyingk 77bd125ef3 Merge pull request #45 from yunyingk/feat/approval-sqlite-engine
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
feat(approval): introduce sqlite rule engine, deterministic gateway, and hose-aipro cli (v0.7.0)
2026-09-06 19:07:40 +08:00
gitea 644c3d2005 fix(cli): unify hose-aipro as multicall symlink alias to hose-use binary 2026-09-06 19:05:07 +08:00
gitea 4e36a1d9a5 feat(approval): introduce sqlite rule engine, deterministic gateway, and hose-aipro cli (v0.7.0)
- Pure Rule Model & AST Parser:
  - Eliminate redundant title field; model rules purely via scope (scene index) and natural language body.
  - Implement AST parser for inline clauses: [action]{硬性|弹性|建议|特殊}.
  - Validate and enforce preference references with @{级别} syntax, strictly blocking invalid grammar.

- Embedded SQLite Database & Repository:
  - Native bun:sqlite integration with zero external dependencies, stored at ~/.config/hose-use/approval.db.
  - 5 core schemas: rules, preferences, approval_runs, approval_findings, and aipro_logs.
  - Support deduplicated scope indexing (listScopes with 1-based indices) and scope drill-down (getScopeDetail).

- Bill Requisition & Backlog Query Extension:
  - Add formatFlowAsBill adapter in domains/bill/tools.ts.
  - Fall back to flow and backlog inspection when bills are not found in invoice endpoints, unlocking full structured inspection for requisitions (such as S26000001) and loan requests.

- Deterministic Approval Gateway & Lifecycle:
  - Enforce mandatory approval lifecycle: points -> checklist -> review -> decide.
  - Physical gateway blocking: forbid decision if audit checklist is missing or empty, or if pending points remain unverified.
  - Hard tier severance: automatically sever and throw GatewayBlockError on approval attempts violating {硬性} clauses.

- Dedicated hose-aipro Global CLI & Immutable Audit Ledger:
  - Register secondary global binary hose-aipro alongside hose-use in package.json and build-binary.mjs.
  - Automatically record every AI Pro invocation, document context, args snapshot, operator, status, and verdict in aipro_logs.
  - Provide intuitive subcommands: points, checklist, review, decide, logs, rules.
  - Bump project version to v0.7.0 and regenerate OpenAPI bundles.
2026-09-06 19:03:06 +08:00
yunyingk 7c0bdb7518 Merge pull request #44 from yunyingk/feat/update-sources-and-repo-opt
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
feat(cli): enhance update sources, normalize repo, upgrade MCP to 2.0, bump to v0.6.2
2026-09-05 22:32:55 +08:00
gitea 2865728885 feat(cli): enhance update sources, normalize repo, upgrade to MCP 2.0, and bump to v0.6.2 2026-09-05 22:32:39 +08:00
yunyingk eaa2b9391f Merge pull request #43 from yunyingk/fix/update-asset-fallback
fix(update): fall back to GitHub releases when Gitea mirror has empty assets
2026-09-05 22:21:03 +08:00
gitea 51502fada5 fix(update): fall back to GitHub releases when Gitea mirror has empty assets 2026-09-05 22:20:45 +08:00
32 changed files with 3360 additions and 247 deletions

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "hose-use",
"version": "0.6.1",
"version": "0.7.0",
"description": "合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号登录、企业租户切换、单据明细检索、工作流管理、内置 HTTP 服务与常驻守护进程。",
"author": {
"name": "yingqing"
+2 -2
View File
@@ -1,4 +1,4 @@
# hose-use (v0.6.1)
# hose-use (v0.7.0)
合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。
@@ -138,7 +138,7 @@ src/
- **Runtime**: Bun
- **HTTP Client**: ky
- **Schema**: Zod
- **MCP SDK**: @modelcontextprotocol/sdk
- **MCP Protocol**: @modelcontextprotocol/server & @modelcontextprotocol/core (v2.0+)
## 面向 AI 智能体
+7 -161
View File
@@ -5,214 +5,60 @@
"": {
"name": "ekb-mcp",
"dependencies": {
"@modelcontextprotocol/sdk": "^1.29.0",
"@modelcontextprotocol/core": "^2.0.0",
"@modelcontextprotocol/server": "^2.0.0",
"ky": "^2.0.2",
"yaml": "^2.9.0",
"zod": "^4.4.3",
},
"devDependencies": {
"@modelcontextprotocol/client": "^2.0.0",
"@types/bun": "^1.3.14",
"typescript": "^5.9.3",
},
},
},
"packages": {
"@hono/node-server": ["@hono/node-server@1.19.14", "", { "peerDependencies": { "hono": "^4" } }, "sha512-GwtvgtXxnWsucXvbQXkRgqksiH2Qed37H9xHZocE5sA3N8O8O8/8FA3uclQXxXVzc9XBZuEOMK7+r02FmSpHtw=="],
"@modelcontextprotocol/client": ["@modelcontextprotocol/client@2.0.0", "", { "dependencies": { "@modelcontextprotocol/core": "2.0.0", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "jose": "^6.1.3", "pkce-challenge": "^5.0.0", "zod": "^4.2.0" } }, "sha512-8f1OghQ2rjzIOfqgUCP+8GiUWqRs89njoWLNqAe8kWmDePv3s1fZXseej+QXemssEuuOvLLmLO/kqM3IQHtISw=="],
"@modelcontextprotocol/sdk": ["@modelcontextprotocol/sdk@1.29.0", "", { "dependencies": { "@hono/node-server": "^1.19.9", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "content-type": "^1.0.5", "cors": "^2.8.5", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "express": "^5.2.1", "express-rate-limit": "^8.2.1", "hono": "^4.11.4", "jose": "^6.1.3", "json-schema-typed": "^8.0.2", "pkce-challenge": "^5.0.0", "raw-body": "^3.0.0", "zod": "^3.25 || ^4.0", "zod-to-json-schema": "^3.25.1" }, "peerDependencies": { "@cfworker/json-schema": "^4.1.1" }, "optionalPeers": ["@cfworker/json-schema"] }, "sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ=="],
"@modelcontextprotocol/core": ["@modelcontextprotocol/core@2.0.0", "", { "dependencies": { "zod": "^4.2.0" } }, "sha512-pJCEwGG7Lfr/+PQp9ZTwKXNeO5wzbfKL7H3MYpCorM4oFBoQrdjnBgEoqG+RjhsvS1FKrDbKux+M1HhlnGWqcA=="],
"@modelcontextprotocol/server": ["@modelcontextprotocol/server@2.0.0", "", { "dependencies": { "@modelcontextprotocol/core": "2.0.0", "zod": "^4.2.0" } }, "sha512-YhHWdHfpFMQfd0prsEnxKeS3Qz3ytIGmsS0sth4KDjnacIT7hxk6hXHkJ9KysxlkvTM+WZAtQbbcUhdoP4Hvtw=="],
"@types/bun": ["@types/bun@1.3.14", "", { "dependencies": { "bun-types": "1.3.14" } }, "sha512-h1hFqFVcvAvD9j9K7ZW7vd82aSA+rTdznZa+5bwvCwqSB1jmmfLcbIWhOLx1/+boy/xmjgCs/OMUL8hRJSmnPw=="],
"@types/node": ["@types/node@25.8.0", "", { "dependencies": { "undici-types": ">=7.24.0 <7.24.7" } }, "sha512-TCFSk8IZh+iLX1xtksoBVtdmgL+1IX0fC9BeU4QqFSuNdN/K+HUlhqOzEmSYYpZUVsLYcPqc9KX+60iDuninSQ=="],
"accepts": ["accepts@2.0.0", "", { "dependencies": { "mime-types": "^3.0.0", "negotiator": "^1.0.0" } }, "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng=="],
"ajv": ["ajv@8.20.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="],
"ajv-formats": ["ajv-formats@3.0.1", "", { "dependencies": { "ajv": "^8.0.0" } }, "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ=="],
"body-parser": ["body-parser@2.2.2", "", { "dependencies": { "bytes": "^3.1.2", "content-type": "^1.0.5", "debug": "^4.4.3", "http-errors": "^2.0.0", "iconv-lite": "^0.7.0", "on-finished": "^2.4.1", "qs": "^6.14.1", "raw-body": "^3.0.1", "type-is": "^2.0.1" } }, "sha512-oP5VkATKlNwcgvxi0vM0p/D3n2C3EReYVX+DNYs5TjZFn/oQt2j+4sVJtSMr18pdRr8wjTcBl6LoV+FUwzPmNA=="],
"bun-types": ["bun-types@1.3.14", "", { "dependencies": { "@types/node": "*" } }, "sha512-4N0ig0fEomHt5R0KCFWjovxow98rIoRwKolrYdCcknNwMekCXRnWEUvgu5soYV8QXtVsrUD8B95MBOZGPvr6KQ=="],
"bytes": ["bytes@3.1.2", "", {}, "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg=="],
"call-bind-apply-helpers": ["call-bind-apply-helpers@1.0.2", "", { "dependencies": { "es-errors": "^1.3.0", "function-bind": "^1.1.2" } }, "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ=="],
"call-bound": ["call-bound@1.0.4", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "get-intrinsic": "^1.3.0" } }, "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg=="],
"content-disposition": ["content-disposition@1.1.0", "", {}, "sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g=="],
"content-type": ["content-type@1.0.5", "", {}, "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA=="],
"cookie": ["cookie@0.7.2", "", {}, "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w=="],
"cookie-signature": ["cookie-signature@1.2.2", "", {}, "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg=="],
"cors": ["cors@2.8.6", "", { "dependencies": { "object-assign": "^4", "vary": "^1" } }, "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw=="],
"cross-spawn": ["cross-spawn@7.0.6", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA=="],
"debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="],
"depd": ["depd@2.0.0", "", {}, "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw=="],
"dunder-proto": ["dunder-proto@1.0.1", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", "gopd": "^1.2.0" } }, "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A=="],
"ee-first": ["ee-first@1.1.1", "", {}, "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow=="],
"encodeurl": ["encodeurl@2.0.0", "", {}, "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg=="],
"es-define-property": ["es-define-property@1.0.1", "", {}, "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g=="],
"es-errors": ["es-errors@1.3.0", "", {}, "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw=="],
"es-object-atoms": ["es-object-atoms@1.1.1", "", { "dependencies": { "es-errors": "^1.3.0" } }, "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA=="],
"escape-html": ["escape-html@1.0.3", "", {}, "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow=="],
"etag": ["etag@1.8.1", "", {}, "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg=="],
"eventsource": ["eventsource@3.0.7", "", { "dependencies": { "eventsource-parser": "^3.0.1" } }, "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA=="],
"eventsource-parser": ["eventsource-parser@3.0.8", "", {}, "sha512-70QWGkr4snxr0OXLRWsFLeRBIRPuQOvt4s8QYjmUlmlkyTZkRqS7EDVRZtzU3TiyDbXSzaOeF0XUKy8PchzukQ=="],
"express": ["express@5.2.1", "", { "dependencies": { "accepts": "^2.0.0", "body-parser": "^2.2.1", "content-disposition": "^1.0.0", "content-type": "^1.0.5", "cookie": "^0.7.1", "cookie-signature": "^1.2.1", "debug": "^4.4.0", "depd": "^2.0.0", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "etag": "^1.8.1", "finalhandler": "^2.1.0", "fresh": "^2.0.0", "http-errors": "^2.0.0", "merge-descriptors": "^2.0.0", "mime-types": "^3.0.0", "on-finished": "^2.4.1", "once": "^1.4.0", "parseurl": "^1.3.3", "proxy-addr": "^2.0.7", "qs": "^6.14.0", "range-parser": "^1.2.1", "router": "^2.2.0", "send": "^1.1.0", "serve-static": "^2.2.0", "statuses": "^2.0.1", "type-is": "^2.0.1", "vary": "^1.1.2" } }, "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw=="],
"express-rate-limit": ["express-rate-limit@8.5.2", "", { "dependencies": { "ip-address": "^10.2.0" }, "peerDependencies": { "express": ">= 4.11" } }, "sha512-5Kb34ipNX694DH48vN9irak1Qx30nb0PLYHXfJgw4YEjiC3ZEmZJhwOp+VfiCYwFzvFTdB9QkArYS5kXa2cx2A=="],
"fast-deep-equal": ["fast-deep-equal@3.1.3", "", {}, "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="],
"fast-uri": ["fast-uri@3.1.2", "", {}, "sha512-rVjf7ArG3LTk+FS6Yw81V1DLuZl1bRbNrev6Tmd/9RaroeeRRJhAt7jg/6YFxbvAQXUCavSoZhPPj6oOx+5KjQ=="],
"finalhandler": ["finalhandler@2.1.1", "", { "dependencies": { "debug": "^4.4.0", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "on-finished": "^2.4.1", "parseurl": "^1.3.3", "statuses": "^2.0.1" } }, "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA=="],
"forwarded": ["forwarded@0.2.0", "", {}, "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow=="],
"fresh": ["fresh@2.0.0", "", {}, "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A=="],
"function-bind": ["function-bind@1.1.2", "", {}, "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA=="],
"get-intrinsic": ["get-intrinsic@1.3.0", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "es-define-property": "^1.0.1", "es-errors": "^1.3.0", "es-object-atoms": "^1.1.1", "function-bind": "^1.1.2", "get-proto": "^1.0.1", "gopd": "^1.2.0", "has-symbols": "^1.1.0", "hasown": "^2.0.2", "math-intrinsics": "^1.1.0" } }, "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ=="],
"get-proto": ["get-proto@1.0.1", "", { "dependencies": { "dunder-proto": "^1.0.1", "es-object-atoms": "^1.0.0" } }, "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g=="],
"gopd": ["gopd@1.2.0", "", {}, "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg=="],
"has-symbols": ["has-symbols@1.1.0", "", {}, "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ=="],
"hasown": ["hasown@2.0.3", "", { "dependencies": { "function-bind": "^1.1.2" } }, "sha512-ej4AhfhfL2Q2zpMmLo7U1Uv9+PyhIZpgQLGT1F9miIGmiCJIoCgSmczFdrc97mWT4kVY72KA+WnnhJ5pghSvSg=="],
"hono": ["hono@4.12.19", "", {}, "sha512-xa3eYXYXx68XTT4hZ7dRzsXBhaq85ToSrlUJNoR0gwz/1Ap/CNwX47wfvV7pc/xWhjKVVkLT7zBJy8chhNguqQ=="],
"http-errors": ["http-errors@2.0.1", "", { "dependencies": { "depd": "~2.0.0", "inherits": "~2.0.4", "setprototypeof": "~1.2.0", "statuses": "~2.0.2", "toidentifier": "~1.0.1" } }, "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ=="],
"iconv-lite": ["iconv-lite@0.7.2", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw=="],
"inherits": ["inherits@2.0.4", "", {}, "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="],
"ip-address": ["ip-address@10.2.0", "", {}, "sha512-/+S6j4E9AHvW9SWMSEY9Xfy66O5PWvVEJ08O0y5JGyEKQpojb0K0GKpz/v5HJ/G0vi3D2sjGK78119oXZeE0qA=="],
"ipaddr.js": ["ipaddr.js@1.9.1", "", {}, "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g=="],
"is-promise": ["is-promise@4.0.0", "", {}, "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ=="],
"isexe": ["isexe@2.0.0", "", {}, "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw=="],
"jose": ["jose@6.2.3", "", {}, "sha512-YYVDInQKFJfR/xa3ojUTl8c2KoTwiL1R5Wg9YCydwH0x0B9grbzlg5HC7mMjCtUJjbQ/YnGEZIhI5tCgfTb4Hw=="],
"json-schema-traverse": ["json-schema-traverse@1.0.0", "", {}, "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="],
"json-schema-typed": ["json-schema-typed@8.0.2", "", {}, "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA=="],
"ky": ["ky@2.0.2", "", {}, "sha512-/GmXpo9F9W+f8n4Ivr2iH+7h7wL7jLbLKWkMlpflcCRb6kGjBfTlASEXaZ9qUgNTn4VgS0P2pwxxzQ4EM6Ulgg=="],
"math-intrinsics": ["math-intrinsics@1.1.0", "", {}, "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g=="],
"media-typer": ["media-typer@1.1.0", "", {}, "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw=="],
"merge-descriptors": ["merge-descriptors@2.0.0", "", {}, "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g=="],
"mime-db": ["mime-db@1.54.0", "", {}, "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ=="],
"mime-types": ["mime-types@3.0.2", "", { "dependencies": { "mime-db": "^1.54.0" } }, "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A=="],
"ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],
"negotiator": ["negotiator@1.0.0", "", {}, "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg=="],
"object-assign": ["object-assign@4.1.1", "", {}, "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg=="],
"object-inspect": ["object-inspect@1.13.4", "", {}, "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew=="],
"on-finished": ["on-finished@2.4.1", "", { "dependencies": { "ee-first": "1.1.1" } }, "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg=="],
"once": ["once@1.4.0", "", { "dependencies": { "wrappy": "1" } }, "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w=="],
"parseurl": ["parseurl@1.3.3", "", {}, "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ=="],
"path-key": ["path-key@3.1.1", "", {}, "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q=="],
"path-to-regexp": ["path-to-regexp@8.4.2", "", {}, "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA=="],
"pkce-challenge": ["pkce-challenge@5.0.1", "", {}, "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ=="],
"proxy-addr": ["proxy-addr@2.0.7", "", { "dependencies": { "forwarded": "0.2.0", "ipaddr.js": "1.9.1" } }, "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg=="],
"qs": ["qs@6.15.2", "", { "dependencies": { "side-channel": "^1.1.0" } }, "sha512-Rzq0KEyX/w/tEybncDgdkZrJgVUsUMk3xjh3t5bv3S1HTAtg+uOYt72+ZfwiQwKdysThkTBdL/rTi6HDmX9Ddw=="],
"range-parser": ["range-parser@1.2.1", "", {}, "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg=="],
"raw-body": ["raw-body@3.0.2", "", { "dependencies": { "bytes": "~3.1.2", "http-errors": "~2.0.1", "iconv-lite": "~0.7.0", "unpipe": "~1.0.0" } }, "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA=="],
"require-from-string": ["require-from-string@2.0.2", "", {}, "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw=="],
"router": ["router@2.2.0", "", { "dependencies": { "debug": "^4.4.0", "depd": "^2.0.0", "is-promise": "^4.0.0", "parseurl": "^1.3.3", "path-to-regexp": "^8.0.0" } }, "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ=="],
"safer-buffer": ["safer-buffer@2.1.2", "", {}, "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="],
"send": ["send@1.2.1", "", { "dependencies": { "debug": "^4.4.3", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "etag": "^1.8.1", "fresh": "^2.0.0", "http-errors": "^2.0.1", "mime-types": "^3.0.2", "ms": "^2.1.3", "on-finished": "^2.4.1", "range-parser": "^1.2.1", "statuses": "^2.0.2" } }, "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ=="],
"serve-static": ["serve-static@2.2.1", "", { "dependencies": { "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "parseurl": "^1.3.3", "send": "^1.2.0" } }, "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw=="],
"setprototypeof": ["setprototypeof@1.2.0", "", {}, "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw=="],
"shebang-command": ["shebang-command@2.0.0", "", { "dependencies": { "shebang-regex": "^3.0.0" } }, "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA=="],
"shebang-regex": ["shebang-regex@3.0.0", "", {}, "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A=="],
"side-channel": ["side-channel@1.1.0", "", { "dependencies": { "es-errors": "^1.3.0", "object-inspect": "^1.13.3", "side-channel-list": "^1.0.0", "side-channel-map": "^1.0.1", "side-channel-weakmap": "^1.0.2" } }, "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw=="],
"side-channel-list": ["side-channel-list@1.0.1", "", { "dependencies": { "es-errors": "^1.3.0", "object-inspect": "^1.13.4" } }, "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w=="],
"side-channel-map": ["side-channel-map@1.0.1", "", { "dependencies": { "call-bound": "^1.0.2", "es-errors": "^1.3.0", "get-intrinsic": "^1.2.5", "object-inspect": "^1.13.3" } }, "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA=="],
"side-channel-weakmap": ["side-channel-weakmap@1.0.2", "", { "dependencies": { "call-bound": "^1.0.2", "es-errors": "^1.3.0", "get-intrinsic": "^1.2.5", "object-inspect": "^1.13.3", "side-channel-map": "^1.0.1" } }, "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A=="],
"statuses": ["statuses@2.0.2", "", {}, "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw=="],
"toidentifier": ["toidentifier@1.0.1", "", {}, "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA=="],
"type-is": ["type-is@2.1.0", "", { "dependencies": { "content-type": "^2.0.0", "media-typer": "^1.1.0", "mime-types": "^3.0.0" } }, "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA=="],
"typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],
"undici-types": ["undici-types@7.24.6", "", {}, "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg=="],
"unpipe": ["unpipe@1.0.0", "", {}, "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ=="],
"vary": ["vary@1.1.2", "", {}, "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg=="],
"which": ["which@2.0.2", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="],
"wrappy": ["wrappy@1.0.2", "", {}, "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="],
"yaml": ["yaml@2.9.0", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA=="],
"zod": ["zod@4.4.3", "", {}, "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ=="],
"zod-to-json-schema": ["zod-to-json-schema@3.25.2", "", { "peerDependencies": { "zod": "^3.25.28 || ^4" } }, "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA=="],
"type-is/content-type": ["content-type@2.0.0", "", {}, "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ=="],
}
}
+1 -1
View File
@@ -2,7 +2,7 @@
"openapi": "3.1.0",
"info": {
"title": "hose-use API & MCP Tools Specification",
"version": "0.6.1",
"version": "0.7.0",
"description": "Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows."
},
"servers": [
+1 -1
View File
@@ -1,7 +1,7 @@
openapi: 3.1.0
info:
title: hose-use API & MCP Tools Specification
version: 0.6.1
version: 0.7.0
description: >-
Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows.
servers:
+6 -3
View File
@@ -1,14 +1,15 @@
{
"name": "hose-use",
"version": "0.6.1",
"version": "0.7.0",
"module": "src/server.ts",
"type": "module",
"bin": {
"hose-use": "src/cli.ts",
"hose": "src/cli.ts"
"hose-aipro": "src/cli.ts"
},
"scripts": {
"cli": "bun run src/cli.ts",
"aipro": "bun run src/aipro-cli.ts",
"probe": "bun run src/cli.ts probe",
"check": "tsc --noEmit",
"typecheck": "tsc --noEmit",
@@ -24,12 +25,14 @@
"export:workflow-schema": "bun run scripts/export-workflow-schema.ts"
},
"dependencies": {
"@modelcontextprotocol/sdk": "^1.29.0",
"@modelcontextprotocol/core": "^2.0.0",
"@modelcontextprotocol/server": "^2.0.0",
"ky": "^2.0.2",
"yaml": "^2.9.0",
"zod": "^4.4.3"
},
"devDependencies": {
"@modelcontextprotocol/client": "^2.0.0",
"@types/bun": "^1.3.14",
"typescript": "^5.9.3"
}
+15 -5
View File
@@ -1,4 +1,4 @@
import { mkdirSync } from "node:fs";
import { mkdirSync, existsSync, unlinkSync, symlinkSync } from "node:fs";
import { spawnSync } from "node:child_process";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
@@ -29,17 +29,27 @@ if (isAll) {
}
buildTarget(targetArg, config.bunTarget, resolve(root, config.outfile));
} else {
const output = resolve(root, "dist/bin/hose-use");
buildTarget("host", null, output);
const outputHose = resolve(root, "dist/bin/hose-use");
buildTarget("host", null, outputHose, "src/cli.ts");
// Unix Multicall Binary: 创建 hose-aipro -> hose-use 软链接别名
const outputAipro = resolve(root, "dist/bin/hose-aipro");
try {
if (existsSync(outputAipro)) unlinkSync(outputAipro);
symlinkSync("hose-use", outputAipro);
console.log(`[build:binary] created multicall symlink: ${outputAipro} -> hose-use`);
} catch {
// 忽略软链接异常
}
}
function buildTarget(name, bunTarget, output) {
function buildTarget(name, bunTarget, output, entry = "src/cli.ts") {
mkdirSync(dirname(output), { recursive: true });
const buildArgs = ["build", "--compile"];
if (bunTarget) {
buildArgs.push(`--target=${bunTarget}`);
}
buildArgs.push("--outfile", output, "src/cli.ts");
buildArgs.push("--outfile", output, entry);
console.log(`[build:binary] compiling target: ${name} -> ${output}`);
run(bun, buildArgs);
+1 -1
View File
@@ -6,7 +6,7 @@ metadata:
short-description: 合思/易快报企业级 CLI 工具与底层 SDK (v0.6.0)
---
# hose-use (v0.6.1)
# hose-use (v0.7.0)
在具备 MCP 的 AI 智能体环境中,**优先使用 `hose_cli` 单工具网关**,传入 `command: string` 执行;在终端或自动化脚本中,直接调用全局 `hose` 或 `hose-use` 命令行。
本 Skill 是智能体的路由分发层:保持主文档简明,遇到复杂业务时深入查阅对应的专属参考文档(`references/*.md`)。
+440
View File
@@ -0,0 +1,440 @@
#!/usr/bin/env bun
import { parseArgs, stringOption, booleanOption, numberOption } from "./cli/parser.js";
import { printJson, printTable, redactSensitiveText } from "./cli/printer.js";
import { initCorpRuntime } from "./cli/helpers.js";
import { createEkbClient } from "./core/auth/ekb.js";
import {
ApprovalService,
ApprovalRepository,
ApprovalGatewayBlockedError,
FindingCheckStatus,
} from "./domains/approval/index.js";
import { VERSION } from "./version.js";
export async function runAiProCli(rawArgs: string[]): Promise<{ stdout: string; stderr: string; exitCode: number }> {
const parsed = parseArgs(rawArgs);
const runtime = initCorpRuntime({
corpId: stringOption(parsed.options, ["corp", "c"]),
jsonMode: booleanOption(parsed.options, ["json"]),
});
const corp = runtime.selectedCorp;
if (!corp) {
return {
stdout: "",
stderr: "未指定或未找到有效企业。请通过 --corp=<id> 指定企业,或运行 hose-use auth login 登录。\n",
exitCode: 1,
};
}
const client = await createEkbClient(corp);
const corpId = corp.corpId || corp.id;
const repo = new ApprovalRepository();
const service = new ApprovalService(repo);
const positional: string[] = [];
for (let i = 0; i < rawArgs.length; i++) {
const arg = rawArgs[i];
if (arg === "--") {
positional.push(...rawArgs.slice(i + 1));
break;
}
if (arg.startsWith("-")) {
const eqIdx = arg.indexOf("=");
if (eqIdx === -1) {
const flagName = arg.replace(/^--?/, "").toLowerCase();
const isBool = ["raw", "json", "j", "help", "h", "version", "v", "yes", "y", "confirm", "apply", "execute", "run", "do"].includes(flagName);
if (!isBool && i + 1 < rawArgs.length && !rawArgs[i + 1].startsWith("-")) {
i++; // skip option value
}
}
continue;
}
positional.push(arg);
}
const command = (positional[0] || "help").toLowerCase();
const targetSn = positional[1] || stringOption(parsed.options, ["code", "sn", "id", "target"]);
const args = positional.slice(1);
const operator = corp.staffId || corp.name || "AI-Agent";
try {
switch (command) {
// ── 1. 明细级规则注入(出审核要点清单)────────────────────────────────
case "points":
case "inject": {
if (!targetSn) {
throw new Error("请提供单号: hose-aipro points <单号> [--scope <1|场景>]");
}
const scopeOption = stringOption(parsed.options, ["scope", "s"]);
const result = await service.injectAuditPoints(client, corpId, targetSn, {
scope: scopeOption ? (isNaN(Number(scopeOption)) ? scopeOption : Number(scopeOption)) : undefined,
});
repo.logAiProAction({
action: "points",
documentSn: result.bill.billCode,
operator,
args: JSON.stringify(rawArgs),
status: "SUCCESS",
decision: "PENDING",
summary: `注入审核要点成功,共 ${result.findings.length} 条要点(场景: ${result.scope})`,
});
if (runtime.jsonMode) {
return {
stdout: printJson({
sn: result.bill.billCode,
scope: result.scope,
runId: result.run.id,
count: result.findings.length,
findings: result.findings,
}),
stderr: "",
exitCode: 0,
};
}
const headers = ["#", "严格程度", "归属规则", "审核要点内容", "核验状态"];
const rows = result.findings.map((f, i) => [
i + 1,
`[${f.strictness}]`,
f.ruleCode ? `#${f.ruleCode}` : "-",
f.clauseText,
f.checkStatus,
]);
const table = printTable(headers, rows);
const title = `====== [AI PRO] 单据 ${result.bill.billCode} 审核要点清单 (场景: ${result.scope} | 共 ${result.findings.length} 条要点) ======\n`;
const tip =
`\n✅ [已安全登记] 审核要点已固化至数据库审批实例,全流程监控已激活。\n` +
`下一步: 运行 "hose-aipro review ${result.bill.billCode} --eval '...' " 进行事实核验打标。\n` +
`最终决断: 运行 "hose-aipro decide ${result.bill.billCode} --apply --yes" 由确定性网关仲裁审批。\n`;
return { stdout: title + table + tip, stderr: "", exitCode: 0 };
}
// ── 2. 查看审核要点清单与进度(未注入则硬阻断)────────────────────────
case "checklist":
case "list":
case "status": {
if (!targetSn) {
throw new Error("请提供单号: hose-aipro checklist <单号>");
}
const { run, findings } = service.getAuditChecklist(targetSn);
if (!run || findings.length === 0) {
repo.logAiProAction({
action: "checklist",
documentSn: targetSn,
operator,
args: JSON.stringify(rawArgs),
status: "BLOCKED",
summary: "查询审核清单阻断:单据尚未注入任何审核要点",
});
const errorMsg =
`[审批链路阻断] 单据 [${targetSn}] 尚未注入任何明细级审核要点(要点列表为空)!\n` +
`网关安全卡点生效:在要点未注入前,审批链路物理不通!\n` +
`请先执行: hose-aipro points ${targetSn} 注入明细级审核要点清单。\n`;
return { stdout: "", stderr: errorMsg, exitCode: 1 };
}
if (runtime.jsonMode) {
return {
stdout: printJson({ run, findings }),
stderr: "",
exitCode: 0,
};
}
const headers = ["#", "严格程度", "规则", "审核要点内容", "核验状态", "事实证据 / 说明"];
const rows = findings.map((f, i) => [
i + 1,
`[${f.strictness}]`,
f.ruleCode ? `#${f.ruleCode}` : "-",
f.clauseText,
f.checkStatus === "PASS" ? "✅ PASS" : f.checkStatus === "FAIL" ? "❌ FAIL" : f.checkStatus === "SKIP" ? "➖ SKIP" : "⏳ PENDING",
[f.evidence, f.reasoning].filter(Boolean).join(" | ") || "-",
]);
const table = printTable(headers, rows);
const pendingCount = findings.filter((f) => f.checkStatus === "PENDING").length;
const title = `====== [AI PRO] 单据 ${targetSn} 审核清单核验进度 (总数: ${findings.length} | 待核验: ${pendingCount} | 决策: ${run.decision}) ======\n`;
return { stdout: title + table, stderr: "", exitCode: 0 };
}
// ── 3. 事实核验打标录入 ───────────────────────────────────────────────
case "review":
case "eval":
case "evaluate": {
if (!targetSn) {
throw new Error("请提供单号: hose-aipro review <单号> --eval '...'");
}
const evalStr = stringOption(parsed.options, ["eval", "findings", "e"]);
const pointIndex = numberOption(parsed.options, ["point", "p", "index", "i"], 0);
const statusInput = stringOption(parsed.options, ["status", "state"])?.toUpperCase() as FindingCheckStatus | undefined;
const evidence = stringOption(parsed.options, ["evidence", "proof"]);
const reasoning = stringOption(parsed.options, ["reasoning", "reason", "r"]);
const updates: Array<{
index?: number;
id?: string;
status: FindingCheckStatus;
evidence?: string;
reasoning?: string;
}> = [];
if (typeof pointIndex === "number" && pointIndex > 0 && statusInput) {
updates.push({ index: pointIndex, status: statusInput, evidence, reasoning });
} else if (evalStr) {
const segments = evalStr.split(";").map((s) => s.trim()).filter(Boolean);
for (const seg of segments) {
const match = seg.match(/^(\d+)\s*=\s*(PASS|FAIL|SKIP)(?::(.*))?$/i);
if (match) {
const idx = parseInt(match[1], 10);
const status = match[2].toUpperCase() as FindingCheckStatus;
const desc = match[3]?.trim();
updates.push({ index: idx, status, evidence: desc, reasoning: desc });
}
}
}
if (updates.length === 0) {
throw new Error(
`请提供核验判定参数,例如:\n` +
` hose-aipro review ${targetSn} --eval "1=PASS; 2=FAIL:未上传特批邮件; 3=SKIP"\n` +
` 或: hose-aipro review ${targetSn} --point 2 --status FAIL --reason "缺少特批邮件"`
);
}
const updatedFindings = service.evaluateAuditPoints(targetSn, updates);
const pendingCount = updatedFindings.filter((f) => f.checkStatus === "PENDING").length;
repo.logAiProAction({
action: "review",
documentSn: targetSn,
operator,
args: JSON.stringify(rawArgs),
status: "SUCCESS",
summary: `已录入 ${updates.length} 处要点核验事实(待核验剩余: ${pendingCount} 项)`,
});
const headers = ["#", "严格程度", "审核要点内容", "核验状态", "事实证据与说明"];
const rows = updatedFindings.map((f, i) => [
i + 1,
`[${f.strictness}]`,
f.clauseText,
f.checkStatus === "PASS" ? "✅ PASS" : f.checkStatus === "FAIL" ? "❌ FAIL" : f.checkStatus === "SKIP" ? "➖ SKIP" : "⏳ PENDING",
[f.evidence, f.reasoning].filter(Boolean).join(" | ") || "-",
]);
const table = printTable(headers, rows);
const msg =
`====== [AI PRO] 单据 ${targetSn} 事实核验已登记入库 (待核验剩余: ${pendingCount} 项) ======\n` +
table +
(pendingCount === 0
? `\n🎉 [事实全部闭环] 所有要点已完成事实核验!可运行确定性网关仲裁: hose-aipro decide ${targetSn} --apply --yes\n`
: `\n⏳ [待续] 尚有 ${pendingCount} 项处于 PENDING,请继续核验。\n`);
return { stdout: msg, stderr: "", exitCode: 0 };
}
// ── 4. 确定性网关仲裁决断与执行 ───────────────────────────────────────
case "decide":
case "approve":
case "reject": {
if (!targetSn) {
throw new Error("请提供单号: hose-aipro decide <单号> [--apply] [--yes]");
}
const apply = booleanOption(parsed.options, ["apply", "execute", "run", "do"]);
if (apply) {
const confirmed = booleanOption(parsed.options, ["yes", "y", "confirm"]);
if (!confirmed) {
if (!process.stdin.isTTY || !process.stdout.isTTY) {
throw new Error("开启 --apply 会真实改变单据流转状态,请显式添加 --yes 确认。");
}
const { prompt } = await import("./cli/helpers.js");
const ans = await prompt("[AI PRO] 即将向合思系统真实执行审批流转/意见留痕,确认执行?输入 yes: ");
if (!/^(y|yes|是)$/i.test(ans.trim())) throw new Error("已取消审批操作");
}
}
const requestedAction = command === "approve" ? "approve" : command === "reject" ? "reject" : (stringOption(parsed.options, ["action"]) as any);
const userComment = stringOption(parsed.options, ["comment", "message", "m"]);
const decisionResult = await service.decideAudit(client, corpId, targetSn, {
requestedAction,
apply,
comment: userComment,
});
repo.logAiProAction({
action: "decide",
documentSn: targetSn,
operator,
args: JSON.stringify(rawArgs),
status: "SUCCESS",
decision: decisionResult.decision,
summary: `网关仲裁完成: ${decisionResult.decision} (硬性违规: ${decisionResult.hardFailedCount}, 弹性违规: ${decisionResult.elasticFailedCount})`,
});
if (runtime.jsonMode) {
return {
stdout: printJson(decisionResult),
stderr: "",
exitCode: 0,
};
}
const outLines: string[] = [];
outLines.push(`\n====== [AI PRO] 合思确定性网关仲裁决断书 (单号: ${targetSn}) ======`);
outLines.push(`网关决策 : ${decisionResult.decision}`);
outLines.push(`违规统计 : 硬性 ${decisionResult.hardFailedCount} 项 | 弹性 ${decisionResult.elasticFailedCount} 项 | 建议 ${decisionResult.suggestFailedCount} 项 | 特殊 ${decisionResult.specialFailedCount} 项`);
if (apply) {
outLines.push(`下游动作 : 已安全真实执行 [${decisionResult.appliedAction}] 动作`);
} else {
outLines.push(`执行模式 : 仿真预审 (Dry Run)。若需执行下游审批流转,请追加 --apply --yes`);
}
outLines.push(`\n--- 审计意见留痕快照 ---\n${decisionResult.decisionSummary}\n`);
return { stdout: outLines.join("\n"), stderr: "", exitCode: 0 };
}
// ── 5. 全流程监控流水查看 (Audit Logs) ────────────────────────────────
case "logs":
case "log":
case "history":
case "trail": {
const limit = numberOption(parsed.options, ["limit", "n"], 50) ?? 50;
const logs = repo.listAiProLogs(targetSn || undefined, limit);
if (runtime.jsonMode) {
return {
stdout: printJson({ total: logs.length, logs }),
stderr: "",
exitCode: 0,
};
}
if (logs.length === 0) {
return {
stdout: `[AI PRO 监控流水] 暂无任何登记日志记录${targetSn ? ` (单号: ${targetSn})` : ""}。\n`,
stderr: "",
exitCode: 0,
};
}
const headers = ["#", "发生时间", "动作 (Action)", "单号", "操作人", "状态", "网关决策", "摘要说明"];
const rows = logs.map((l, i) => [
i + 1,
new Date(l.createdAt).toLocaleString("zh-CN"),
l.action,
l.documentSn || "-",
l.operator || "-",
l.status === "SUCCESS" ? "✅ SUCCESS" : l.status === "BLOCKED" ? "🚫 BLOCKED" : "❌ ERROR",
l.decision || "-",
l.summary || "-",
]);
const table = printTable(headers, rows);
const title = `====== [AI PRO 全流程监控流水账本] (共登记 ${logs.length} 条记录) ======\n`;
return { stdout: title + table, stderr: "", exitCode: 0 };
}
// ── 6. 规约快捷查看 ───────────────────────────────────────────────────
case "rules":
case "rule":
case "scopes": {
const scopes = repo.listScopes();
const headers = ["索引号", "适用场景 (Scope)", "有效规则数", "包含规则编号"];
const rows = scopes.map((s) => [
s.index,
s.scope,
s.ruleCount,
s.ruleCodes.map((c) => `#${c}`).join(", "),
]);
const table = printTable(headers, rows);
const title = `====== [AI PRO] 规约场景索引库 (共 ${scopes.length} 个场景) ======\n`;
return { stdout: title + table, stderr: "", exitCode: 0 };
}
// ── 7. 帮助 ───────────────────────────────────────────────────────────
case "help":
default: {
const helpText = `
合思 AI PRO 确定性审批仲裁网关 CLI (hose-aipro) v${VERSION}
一切操作在本地 SQLite 强受控、全流程监控、不可篡改审计留痕。
核心工作流:
1. 规则注入 (出明细级审核要点清单):
hose-aipro points <单号> [--scope <索引号|场景>]
2. 查看审核要点清单与核验进度 (未注入则硬阻断):
hose-aipro checklist <单号>
3. 逐项录入事实核验打标:
hose-aipro review <单号> --eval "1=PASS; 2=FAIL:证据说明; 3=SKIP"
hose-aipro review <单号> --point 1 --status FAIL --reason "缺少发票"
4. 确定性网关仲裁与流转执行 (硬性条款物理切断同意分支):
hose-aipro decide <单号> # 预审仿真 (Dry Run)
hose-aipro decide <单号> --apply --yes # 真实驱动下游审批/驳回/评论
5. 全流程监控日志流水查看:
hose-aipro logs [单号] # 追溯所有 AI PRO 操作流水
6. 查看审批规约场景:
hose-aipro rules # 查看所有场景与规则分布
`;
return { stdout: helpText.trim() + "\n", stderr: "", exitCode: 0 };
}
}
} catch (err: any) {
// 将阻断或异常统一记录至审计日志
if (err instanceof ApprovalGatewayBlockedError) {
repo.logAiProAction({
action: command,
documentSn: targetSn,
operator,
args: JSON.stringify(rawArgs),
status: "BLOCKED",
summary: err.message.replace(/\n+/g, " "),
});
return {
stdout: "",
stderr: `\n${err.message}\n`,
exitCode: 1,
};
}
repo.logAiProAction({
action: command,
documentSn: targetSn,
operator,
args: JSON.stringify(rawArgs),
status: "ERROR",
summary: String(err?.message || err),
});
return {
stdout: "",
stderr: `[AI PRO 错误] ${err?.message || err}\n`,
exitCode: 1,
};
}
}
// 直接作为可执行脚本运行时
if (import.meta.main) {
const rawArgs = process.argv.slice(2);
const result = await runAiProCli(rawArgs);
if (result.stdout) process.stdout.write(redactSensitiveText(result.stdout));
if (result.stderr) process.stderr.write(redactSensitiveText(result.stderr));
process.exit(result.exitCode);
}
+12 -3
View File
@@ -14,11 +14,20 @@ process.stderr.on("error", (err: any) => {
const entryFile = fileURLToPath(import.meta.url);
const appRoot = dirname(dirname(entryFile));
const result = await runCli(process.argv.slice(2), {
appRoot,
entryFile,
// Unix Multicall Binary Pattern: 检测是否通过 hose-aipro 符号链接/别名唤起
const candidates = [process.argv0, process.argv[1], process.argv[0]].filter(Boolean) as string[];
const isAiPro = candidates.some((c) => {
const base = c.split("/").pop() || "";
return base.includes("hose-aipro") || base === "aipro" || base.includes("aipro-cli");
});
const result = isAiPro
? await (await import("./aipro-cli.js")).runAiProCli(process.argv.slice(2))
: await runCli(process.argv.slice(2), {
appRoot,
entryFile,
});
try {
if (result.stdout) process.stdout.write(result.stdout);
} catch (err: any) {
+330
View File
@@ -0,0 +1,330 @@
import { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
import { printJson, printTable } from "../printer.js";
import { stringOption, booleanOption, numberOption } from "../parser.js";
import { createEkbClient } from "../../core/auth/ekb.js";
import {
ApprovalService,
ApprovalGatewayBlockedError,
FindingCheckStatus,
} from "../../domains/approval/index.js";
export async function handleApprovalCommand(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const corp = runtime.selectedCorp;
if (!corp) {
throw new Error(
"未指定或未找到有效企业。请通过 --corp=<id> 指定企业,或运行 hose-use auth login 登录。"
);
}
const client = await createEkbClient(corp);
const corpId = corp.corpId || corp.id;
const service = new ApprovalService();
// 解析命令层级:
// 形式 A: hose-use approval audit points S26000001
// 形式 B: hose-use approval points S26000001
// 形式 C: hose-use approval audit S26000001
let subAction = parsed.action?.toLowerCase();
let args = [...parsed.args];
if (subAction === "audit" && args.length > 0) {
const candidateSub = args[0]?.toLowerCase();
if (["points", "inject", "checklist", "list", "review", "eval", "evaluate", "decide", "approve", "reject"].includes(candidateSub)) {
subAction = candidateSub;
args.shift();
}
}
const targetSn = args[0] || stringOption(parsed.options, ["code", "sn", "target", "id"]);
switch (subAction) {
// ── 1. 规则注入与出明细级审核要点清单 ─────────────────────────────────────
case "points":
case "inject": {
if (!targetSn) {
throw new Error("请提供单号或单据 ID: hose-use approval audit points <单号>");
}
const scopeOption = stringOption(parsed.options, ["scope", "s"]);
const result = await service.injectAuditPoints(client, corpId, targetSn, {
scope: scopeOption ? (isNaN(Number(scopeOption)) ? scopeOption : Number(scopeOption)) : undefined,
});
if (runtime.jsonMode) {
return {
stdout: printJson(
{
sn: result.bill.billCode,
scope: result.scope,
runId: result.run.id,
count: result.findings.length,
findings: result.findings,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
const headers = ["#", "严格程度", "归属规则", "审核要点内容", "核验状态"];
const rows = result.findings.map((f, i) => [
i + 1,
`[${f.strictness}]`,
f.ruleCode ? `#${f.ruleCode}` : "-",
f.clauseText,
f.checkStatus,
]);
const table = printTable(headers, rows);
const title = `====== 单据 ${result.bill.billCode} 明细级审核要点清单 (场景: ${result.scope} | 共 ${result.findings.length} 条要点) ======\n`;
const tip =
`\n[要点注入完成] 审核要点已固化至审批实例,审批链路已激活!\n` +
`下一步: 请对要点进行事实核验判定: hose-use approval audit review ${result.bill.billCode} --eval "1=PASS; 2=FAIL:证据说明; ..."\n` +
`完成核验后,由确定性网关仲裁审批: hose-use approval audit decide ${result.bill.billCode} --apply --yes\n`;
return {
stdout: title + table + tip,
stderr: "",
exitCode: 0,
};
}
// ── 2. 查看当前审核要点清单与核验状态 ─────────────────────────────────────
case "checklist":
case "list":
case "status": {
if (!targetSn) {
throw new Error("请提供单号或单据 ID: hose-use approval audit checklist <单号>");
}
const { run, findings } = service.getAuditChecklist(targetSn);
if (!run || findings.length === 0) {
const errorMsg =
`[审批链路阻断] 单据 [${targetSn}] 尚未注入任何明细级审核要点(要点列表为空)!\n` +
`审批链路当前物理不通!请先执行: hose-use approval audit points ${targetSn} 注入审核要点清单。\n`;
return { stdout: "", stderr: errorMsg, exitCode: 1 };
}
if (runtime.jsonMode) {
return {
stdout: printJson({ run, findings }, runtime.outputOptions),
stderr: "",
exitCode: 0,
};
}
const headers = ["#", "严格程度", "规则", "审核要点内容", "核验状态", "事实证据 / 推理说明"];
const rows = findings.map((f, i) => [
i + 1,
`[${f.strictness}]`,
f.ruleCode ? `#${f.ruleCode}` : "-",
f.clauseText,
f.checkStatus === "PASS" ? "✅ PASS" : f.checkStatus === "FAIL" ? "❌ FAIL" : f.checkStatus === "SKIP" ? "➖ SKIP" : "⏳ PENDING",
[f.evidence, f.reasoning].filter(Boolean).join(" | ") || "-",
]);
const table = printTable(headers, rows);
const pendingCount = findings.filter((f) => f.checkStatus === "PENDING").length;
const title = `====== 单据 ${targetSn} 审核要点核验进度 (总计: ${findings.length} | 待核验: ${pendingCount} | 运行决策: ${run.decision}) ======\n`;
return {
stdout: title + table,
stderr: "",
exitCode: 0,
};
}
// ── 3. 逐项核验事实打标 ──────────────────────────────────────────────────
case "review":
case "eval":
case "evaluate": {
if (!targetSn) {
throw new Error("请提供单号: hose-use approval audit review <单号> --eval '...'");
}
const evalStr = stringOption(parsed.options, ["eval", "findings", "data", "e"]);
const pointIndex = numberOption(parsed.options, ["point", "p", "index", "i"], 0);
const statusInput = stringOption(parsed.options, ["status", "state"])?.toUpperCase() as FindingCheckStatus | undefined;
const evidence = stringOption(parsed.options, ["evidence", "proof"]);
const reasoning = stringOption(parsed.options, ["reasoning", "reason", "r"]);
const updates: Array<{
index?: number;
id?: string;
status: FindingCheckStatus;
evidence?: string;
reasoning?: string;
}> = [];
if (typeof pointIndex === "number" && pointIndex > 0 && statusInput) {
updates.push({
index: pointIndex,
status: statusInput,
evidence,
reasoning,
});
} else if (evalStr) {
// 解析便捷语法: "1=FAIL:未上传发票; 2=PASS; 3=SKIP; 4=FAIL:大连住宿超标且无特批"
const segments = evalStr.split(";").map((s) => s.trim()).filter(Boolean);
for (const seg of segments) {
const match = seg.match(/^(\d+)\s*=\s*(PASS|FAIL|SKIP)(?::(.*))?$/i);
if (match) {
const idx = parseInt(match[1], 10);
const status = match[2].toUpperCase() as FindingCheckStatus;
const desc = match[3]?.trim();
updates.push({
index: idx,
status,
evidence: desc,
reasoning: desc,
});
}
}
}
if (updates.length === 0) {
throw new Error(
`请提供核验判定参数,例如:\n` +
` hose-use approval audit review ${targetSn} --eval "1=PASS; 2=FAIL:未上传特批邮件; 3=SKIP"\n` +
` 或: hose-use approval audit review ${targetSn} --point 2 --status FAIL --reason "缺少特批邮件"`
);
}
try {
const updatedFindings = service.evaluateAuditPoints(targetSn, updates);
const headers = ["#", "严格程度", "审核要点内容", "核验状态", "事实证据与说明"];
const rows = updatedFindings.map((f, i) => [
i + 1,
`[${f.strictness}]`,
f.clauseText,
f.checkStatus === "PASS" ? "✅ PASS" : f.checkStatus === "FAIL" ? "❌ FAIL" : f.checkStatus === "SKIP" ? "➖ SKIP" : "⏳ PENDING",
[f.evidence, f.reasoning].filter(Boolean).join(" | ") || "-",
]);
const table = printTable(headers, rows);
const pendingCount = updatedFindings.filter((f) => f.checkStatus === "PENDING").length;
const msg =
`====== 单据 ${targetSn} 核验判定已更新 (待核验剩余: ${pendingCount} 项) ======\n` +
table +
(pendingCount === 0
? `\n[核验全部闭环] 所有要点已完成事实核验!可运行确定性网关仲裁: hose-use approval audit decide ${targetSn} --apply --yes\n`
: `\n[待续] 尚有 ${pendingCount} 项处于 PENDING,请继续核验。\n`);
return { stdout: msg, stderr: "", exitCode: 0 };
} catch (err: any) {
if (err instanceof ApprovalGatewayBlockedError) {
return { stdout: "", stderr: `${err.message}\n`, exitCode: 1 };
}
throw err;
}
}
// ── 4. 确定性网关仲裁与审批决断 ──────────────────────────────────────────
case "decide":
case "approve":
case "reject": {
if (!targetSn) {
throw new Error("请提供单号: hose-use approval audit decide <单号> [--apply] [--yes]");
}
const apply = booleanOption(parsed.options, ["apply", "execute", "run", "do"]);
if (apply) {
const confirmed = booleanOption(parsed.options, ["yes", "y", "confirm"]);
if (!confirmed) {
if (!process.stdin.isTTY || !process.stdout.isTTY) {
throw new Error("开启 --apply 会真实改变单据流转状态,请显式添加 --yes 确认。");
}
const { prompt } = await import("../helpers.js");
const ans = await prompt("网关将向合思系统真实执行审批/驳回/留痕,确认继续?输入 yes: ");
if (!/^(y|yes|是)$/i.test(ans.trim())) throw new Error("已取消审批操作");
}
}
const requestedAction = subAction === "approve" ? "approve" : subAction === "reject" ? "reject" : (stringOption(parsed.options, ["action"]) as any);
const userComment = stringOption(parsed.options, ["comment", "message", "m"]);
try {
const decisionResult = await service.decideAudit(client, corpId, targetSn, {
requestedAction,
apply,
comment: userComment,
});
if (runtime.jsonMode) {
return {
stdout: printJson(decisionResult, runtime.outputOptions),
stderr: "",
exitCode: 0,
};
}
const outLines: string[] = [];
outLines.push(`\n====== 合思 AI 确定性网关仲裁裁决书 (单号: ${targetSn}) ======`);
outLines.push(`网关决策 : ${decisionResult.decision}`);
outLines.push(`违规统计 : 硬性 ${decisionResult.hardFailedCount} 项 | 弹性 ${decisionResult.elasticFailedCount} 项 | 建议 ${decisionResult.suggestFailedCount} 项 | 特殊 ${decisionResult.specialFailedCount} 项`);
if (apply) {
outLines.push(`下游动作 : 已安全执行 [${decisionResult.appliedAction}] 动作`);
} else {
outLines.push(`执行模式 : 预审仿真 (Dry Run)。若需执行下游审批流转,请追加 --apply --yes`);
}
outLines.push(`\n--- 审计意见文本快照 ---\n${decisionResult.decisionSummary}\n`);
return {
stdout: outLines.join("\n"),
stderr: "",
exitCode: 0,
};
} catch (err: any) {
if (err instanceof ApprovalGatewayBlockedError) {
return {
stdout: "",
stderr: `\n${err.message}\n`,
exitCode: 1,
};
}
throw err;
}
}
// ── 5. 缺省:智能引导 (未注入则出要点,已注入则显示清单) ─────────────────────
case "audit":
case undefined: {
if (!targetSn) {
return {
stdout:
`====== 合思 AI 确定性审批网关 (hose-use approval) ======\n` +
`用法:\n` +
` 1. 出明细级审核要点 (规则注入) : hose-use approval audit points <单号> [--scope <场景>]\n` +
` 2. 查看当前审核要点清单 : hose-use approval audit checklist <单号>\n` +
` 3. 逐项录入事实核验判定 : hose-use approval audit review <单号> --eval "1=PASS; 2=FAIL:说明"\n` +
` 4. 网关确定性仲裁与执行审批 : hose-use approval audit decide <单号> [--apply] [--yes]\n`,
stderr: "",
exitCode: 0,
};
}
// 检查当前是否已注入要点
const { run } = service.getAuditChecklist(targetSn);
if (!run) {
// 自动触发第一步:注入并出审核要点
return await handleApprovalCommand(
{ ...parsed, action: "points", args: [targetSn] },
runtime
);
} else {
// 已有要点,展示清单与进度
return await handleApprovalCommand(
{ ...parsed, action: "checklist", args: [targetSn] },
runtime
);
}
}
default:
throw new Error(`未知的审批网关动作: ${subAction}。请运行 hose-use approval audit 查看帮助。`);
}
}
+32 -8
View File
@@ -48,6 +48,8 @@ async function handleShow(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
defaultCorpId: globalConfig.defaultCorpId || null,
defaultAccountId: globalConfig.defaultAccountId || null,
activeCorp: currentCorp ? { id: currentCorp.id, name: currentCorp.name } : null,
updateRepo: globalConfig.updateRepo || null,
updateSource: globalConfig.updateSource || "auto",
configFile: configPath,
};
@@ -59,11 +61,13 @@ async function handleShow(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
"运行模式 (Mode)": globalConfig.stateful ? "有状态模式 (Stateful - 自动记忆默认企业)" : "无状态模式 (Stateless - 每次需显式传 --corp)",
"默认工作企业": globalConfig.defaultCorpId || "未设置 (使用首个可用企业)",
"当前解析企业": currentCorp ? `${currentCorp.name} (${currentCorp.id})` : "无",
"默认自更新仓库": globalConfig.updateRepo || "官方默认 (yunyingk/hose-use)",
"自更新源偏好": globalConfig.updateSource || "auto (自动择优)",
"配置文件路径": configPath,
});
return {
stdout: `====== 全局运行配置 ======\n${output}\n\n提示:\n 切换模式: hose config mode <stateful|stateless>\n 指定企业: hose corps switch <corpId>\n`,
stdout: `====== 全局运行配置 ======\n${output}\n\n提示:\n 切换模式: hose config mode <stateful|stateless>\n 指定企业: hose corps switch <corpId>\n 更新源设置: hose config set updateSource <auto|github|gitea>\n`,
stderr: "",
exitCode: 0,
};
@@ -95,10 +99,10 @@ async function handleMode(parsed: CliParsedArgs, runtime: CliRuntime): Promise<C
}
async function handleSet(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const key = parsed.args[0];
const rawKey = parsed.args[0];
const val = parsed.args[1];
if (!key || val === undefined) {
if (!rawKey || val === undefined) {
return {
stdout: "",
stderr: "用法: hose config set <key> <val> (如 hose config set defaultCorpId uzU7pcWfScck00)\n",
@@ -106,17 +110,37 @@ async function handleSet(parsed: CliParsedArgs, runtime: CliRuntime): Promise<Cl
};
}
const keyLower = rawKey.toLowerCase();
const partial: Record<string, unknown> = {};
if (key === "stateful") {
let resolvedKey = rawKey;
if (keyLower === "stateful") {
resolvedKey = "stateful";
partial.stateful = val === "true" || val === "1";
} else if (key === "defaultCorpId") {
} else if (keyLower === "defaultcorpid") {
resolvedKey = "defaultCorpId";
partial.defaultCorpId = val;
} else if (key === "defaultAccountId") {
} else if (keyLower === "defaultaccountid") {
resolvedKey = "defaultAccountId";
partial.defaultAccountId = val;
} else if (keyLower === "updaterepo") {
resolvedKey = "updateRepo";
partial.updateRepo = val;
} else if (keyLower === "updatesource") {
resolvedKey = "updateSource";
const srcLower = val.toLowerCase();
if (srcLower !== "auto" && srcLower !== "github" && srcLower !== "gitea") {
return {
stdout: "",
stderr: `不支持的 updateSource 值: ${val}。可选: auto, github, gitea\n`,
exitCode: 1,
};
}
partial.updateSource = srcLower;
} else {
return {
stdout: "",
stderr: `不支持配置键: ${key}。支持: stateful, defaultCorpId, defaultAccountId\n`,
stderr: `不支持配置键: ${rawKey}。支持: stateful, defaultCorpId, defaultAccountId, updateRepo, updateSource\n`,
exitCode: 1,
};
}
@@ -127,7 +151,7 @@ async function handleSet(parsed: CliParsedArgs, runtime: CliRuntime): Promise<Cl
}
return {
stdout: `[SUCCESS] 配置已更新: ${key} = ${val}\n`,
stdout: `[SUCCESS] 配置已更新: ${resolvedKey} = ${val}\n`,
stderr: "",
exitCode: 0,
};
+115
View File
@@ -0,0 +1,115 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { runCli } from "../runner.js";
import { closeApprovalDatabase, getApprovalDatabase } from "../../domains/approval/db.js";
import { ApprovalRepository } from "../../domains/approval/repository.js";
describe("CLI - hose-use rule 规则与场景索引命令", () => {
beforeEach(() => {
process.env.HOSE_APPROVAL_DB = ":memory:";
const db = getApprovalDatabase(":memory:");
const repo = new ApprovalRepository(db);
// 预置几条测试规则 (仅需 适用场景 + 规约正文 两个要素)
repo.createRule({
scope: "差旅报销",
body: "差旅报销时,[必须上传发票]{硬性}。"
});
repo.createRule({
scope: "差旅报销",
body: "差旅报销时,[尽量上传支付凭证]{弹性}。"
});
repo.createRule({
scope: "业务招待",
body: "招待报销时,[必须提供餐饮点餐水单]{硬性}。"
});
});
afterEach(() => {
closeApprovalDatabase();
delete process.env.HOSE_APPROVAL_DB;
});
test("hose-use rule scopes 一键获取去重场景索引列表", async () => {
const res = await runCli(["rule", "scopes", "--json"]);
expect(res.exitCode).toBe(0);
const data = JSON.parse(res.stdout);
expect(data.count).toBe(2);
expect(data.scopes[0].index).toBe(1);
expect(data.scopes[0].scope).toBe("差旅报销");
expect(data.scopes[0].ruleCount).toBe(2);
expect(data.scopes[0].ruleCodes).toEqual([1, 2]);
expect(data.scopes[1].index).toBe(2);
expect(data.scopes[1].scope).toBe("业务招待");
expect(data.scopes[1].ruleCount).toBe(1);
expect(data.scopes[1].ruleCodes).toEqual([3]);
});
test("hose-use rule scope <1> 输入索引号获取该场景下的全部规则明细", async () => {
const res = await runCli(["rule", "scope", "1", "--json"]);
expect(res.exitCode).toBe(0);
const data = JSON.parse(res.stdout);
expect(data.index).toBe(1);
expect(data.scope).toBe("差旅报销");
expect(data.ruleCount).toBe(2);
expect(data.rules.length).toBe(2);
expect(data.rules[0].code).toBe(1);
expect(data.rules[0].parsed.clauses[0].strictness).toBe("硬性");
expect(data.rules[1].code).toBe(2);
expect(data.rules[1].parsed.clauses[0].strictness).toBe("弹性");
});
test("hose-use rule scope <场景名称> 输入名称同样可以获取明细", async () => {
const res = await runCli(["rule", "scope", "业务招待", "--json"]);
expect(res.exitCode).toBe(0);
const data = JSON.parse(res.stdout);
expect(data.index).toBe(2);
expect(data.scope).toBe("业务招待");
expect(data.ruleCount).toBe(1);
expect(data.rules[0].code).toBe(3);
expect(data.rules[0].parsed.clauses[0].action).toBe("必须提供餐饮点餐水单");
});
test("hose-use rule scope <不存在> 返回 1 并提示未找到", async () => {
const res = await runCli(["rule", "scope", "999", "--json"]);
expect(res.exitCode).toBe(1);
const data = JSON.parse(res.stdout);
expect(data.found).toBe(false);
});
test("hose-use rule add 纯双参数 (索引 + 正文) 快速新增并强校验", async () => {
// 成功添加:支持直接传 [适用场景] [正文] 两个参数
const addRes = await runCli([
"rule",
"add",
"办公采购",
"单笔采购大于1万,[必须附采购合同]{硬性};[建议由采购员集中办理]{建议}。",
"--json"
]);
expect(addRes.exitCode).toBe(0);
const addData = JSON.parse(addRes.stdout);
expect(addData.success).toBe(true);
expect(addData.rule.code).toBe(4);
expect(addData.rule.scope).toBe("办公采购");
// 再次调用 scopes 应该出现第 3 个索引
const scopesRes = await runCli(["rule", "scopes", "--json"]);
const scopesData = JSON.parse(scopesRes.stdout);
expect(scopesData.count).toBe(3);
expect(scopesData.scopes[2].scope).toBe("办公采购");
});
test("hose-use rule add 语法错误拦截并阻止入库", async () => {
const failRes = await runCli([
"rule",
"add",
"差旅报销",
"差旅报销时,[必须附发票]{严重}。" // 非法严格程度
]);
expect(failRes.exitCode).not.toBe(0);
expect(failRes.stderr).toContain("非法严格程度");
});
});
+268
View File
@@ -0,0 +1,268 @@
import { ApprovalRepository, parseRuleBody } from "../../domains/approval/index.js";
import { booleanOption, stringOption } from "../parser.js";
import { printJson, printTable } from "../printer.js";
import { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
export async function handleRuleCommand(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const repo = new ApprovalRepository();
const action = (parsed.action || "scopes").toLowerCase();
// 1. 获取所有去重索引(适用场景)列表及对应索引号
// 用法: hose-use rule scopes [--all]
if (["scopes", "scope-list", "indexes", "index"].includes(action)) {
const showAll = booleanOption(parsed.options, ["all"]);
const status = showAll ? undefined : "active";
const scopes = repo.listScopes(status);
if (runtime.jsonMode) {
return {
stdout: printJson({ count: scopes.length, scopes }, runtime.outputOptions),
stderr: "",
exitCode: 0
};
}
const rows = scopes.map((s) => [
s.index,
s.scope,
s.ruleCount,
s.ruleCodes.map((c) => `#${c}`).join(", ") || "-"
]);
const header = `====== 审批规约索引列表 (共 ${scopes.length} 个适用场景) ======\n`;
const table = rows.length
? printTable(["索引号", "适用场景 (Scope)", "规则数", "包含规则编号"], rows)
: "暂无有效规则索引。可使用 hose-use rule add 添加规则。\n";
return {
stdout: `${header}${table}\n提示:输入 "hose-use rule scope <索引号>" 查看该场景下的全部规约明细。\n`,
stderr: "",
exitCode: 0
};
}
// 2. 根据索引号或场景名称,获取该场景下的所有规约明细
// 用法: hose-use rule scope <1|"差旅报销">
if (action === "scope") {
const target = parsed.args[0] || stringOption(parsed.options, ["target", "name", "id", "index"]);
if (!target) {
throw new Error("请提供索引号或适用场景名称: hose-use rule scope <索引号|场景名称>");
}
const detail = repo.getScopeDetail(target);
if (!detail) {
if (runtime.jsonMode) {
return {
stdout: printJson({ found: false, target }, runtime.outputOptions),
stderr: "",
exitCode: 1
};
}
return {
stdout: "",
stderr: `[NOT FOUND] 未找到索引号或场景为 "${target}" 的有效规则。\n提示:可先运行 "hose-use rule scopes" 查看所有可用索引号。\n`,
exitCode: 1
};
}
if (runtime.jsonMode) {
return {
stdout: printJson(detail, runtime.outputOptions),
stderr: "",
exitCode: 0
};
}
const lines: string[] = [
`====== 适用场景 [${detail.index}] ${detail.scope} (共 ${detail.ruleCount} 条规则) ======\n`
];
detail.rules.forEach((r, idx) => {
lines.push(`${idx + 1}. [规则 #${r.code}] (v${r.version})`);
lines.push(` 正文: ${r.body}`);
lines.push(" 审查要点:");
r.parsed.clauses.forEach((c) => {
lines.push(` - [${c.strictness}] ${c.action}`);
});
lines.push("");
});
return {
stdout: lines.join("\n"),
stderr: "",
exitCode: 0
};
}
// 3. 规则列表查询
// 用法: hose-use rule list [--scope <name>] [--status active]
if (action === "list") {
const scope = stringOption(parsed.options, ["scope", "s"]);
const statusOption = stringOption(parsed.options, ["status"]);
const status = (statusOption as any) || "active";
const rules = repo.listRules({ scope, status });
if (runtime.jsonMode) {
return {
stdout: printJson({ count: rules.length, rules }, runtime.outputOptions),
stderr: "",
exitCode: 0
};
}
const rows = rules.map((r) => [
`#${r.code}`,
r.scope,
`v${r.version}`,
r.status,
r.body.length > 35 ? r.body.slice(0, 35) + "..." : r.body,
r.id
]);
const header = `====== 审批规约清单 (共 ${rules.length} 条) ======\n`;
const table = rows.length
? printTable(["编号", "适用场景 (索引)", "版本", "状态", "规约正文预览", "ID"], rows)
: "暂无规则记录。\n";
return { stdout: `${header}${table}\n`, stderr: "", exitCode: 0 };
}
// 4. 查看单条规则详情
// 用法: hose-use rule get <code|id>
if (action === "get" || action === "show") {
const target = parsed.args[0] || stringOption(parsed.options, ["code", "id"]);
if (!target) {
throw new Error("请提供规则编号或 ID: hose-use rule get <编号|ID>");
}
let rule = /^\d+$/.test(target) ? repo.getRuleByCode(Number(target)) : null;
if (!rule) {
rule = repo.getRuleById(target);
}
if (!rule) {
if (runtime.jsonMode) {
return {
stdout: printJson({ found: false, target }, runtime.outputOptions),
stderr: "",
exitCode: 1
};
}
return {
stdout: "",
stderr: `[NOT FOUND] 未找到编号或 ID 为 "${target}" 的规则。\n`,
exitCode: 1
};
}
const parsedRule = parseRuleBody(rule.body);
const result = {
...rule,
parsed: parsedRule
};
if (runtime.jsonMode) {
return {
stdout: printJson(result, runtime.outputOptions),
stderr: "",
exitCode: 0
};
}
const lines: string[] = [
`====== 规则 #${rule.code} 详情 ======\n`,
`规则 ID: ${rule.id}`,
`适用场景: ${rule.scope}`,
`规则版本: v${rule.version}`,
`当前状态: ${rule.status}`,
`规约正文:\n${rule.body}\n`,
`审查要点拆解 (${parsedRule.clauses.length} 项):`
];
parsedRule.clauses.forEach((c) => {
lines.push(` - [${c.strictness}] ${c.action}`);
});
return { stdout: lines.join("\n") + "\n", stderr: "", exitCode: 0 };
}
// 5. 新增规则 (内置语法分析强校验)
// 用法: hose-use rule add <适用场景/索引> <规约正文>
// 或: hose-use rule add --scope <scope> --body <body>
if (action === "add" || action === "create") {
let scope = stringOption(parsed.options, ["scope", "s"]);
let body = stringOption(parsed.options, ["body", "b"]);
if (!scope && parsed.args.length >= 1) {
scope = parsed.args[0];
if (!body && parsed.args.length >= 2) {
body = parsed.args.slice(1).join(" ");
}
}
if (!scope) throw new Error("缺少适用场景/索引参数:请输入索引名称或使用 --scope 指定");
if (!body) throw new Error("缺少规约正文参数:请输入正文或使用 --body 指定,须包含 [动作句式]{硬性|弹性|建议|特殊}");
const rule = repo.createRule({
scope,
body,
status: "active"
});
if (runtime.jsonMode) {
return {
stdout: printJson({ success: true, rule }, runtime.outputOptions),
stderr: "",
exitCode: 0
};
}
return {
stdout: `✓ 成功创建规则 #${rule.code} (ID: ${rule.id})!\n适用场景 (索引): ${rule.scope}\n规约正文: ${rule.body}\n`,
stderr: "",
exitCode: 0
};
}
// 6. 删除规则
// 用法: hose-use rule delete <id>
if (action === "delete" || action === "remove" || action === "rm") {
const target = parsed.args[0] || stringOption(parsed.options, ["id", "code"]);
if (!target) throw new Error("请提供要删除的规则 ID 或编号: hose-use rule delete <ID|编号>");
let ruleId = target;
if (/^\d+$/.test(target)) {
const found = repo.getRuleByCode(Number(target));
if (!found) throw new Error(`未找到编号为 #${target} 的规则`);
ruleId = found.id;
}
const deleted = repo.deleteRule(ruleId);
if (runtime.jsonMode) {
return {
stdout: printJson({ success: deleted, id: ruleId }, runtime.outputOptions),
stderr: "",
exitCode: deleted ? 0 : 1
};
}
return {
stdout: deleted ? `✓ 成功删除规则 (ID: ${ruleId})\n` : `未找到规则 (ID: ${ruleId})\n`,
stderr: "",
exitCode: deleted ? 0 : 1
};
}
throw new Error(
`未知 rule 子命令: "${action}"。\n支持命令:\n` +
` hose-use rule scopes 获取去重场景索引列表与索引号\n` +
` hose-use rule scope <索引号|场景> 获取指定场景下的全部规则明细\n` +
` hose-use rule list 列出全部规则\n` +
` hose-use rule get <编号|ID> 查看规则详情与要点拆解\n` +
` hose-use rule add 添加新规则 (带语法强校验)\n` +
` hose-use rule delete <编号|ID> 删除规则\n`
);
}
+32 -1
View File
@@ -1,5 +1,12 @@
import { describe, expect, test } from "bun:test";
import { compareSemVer, isNewerVersion, matchAssetForPlatform, type GitHubAsset } from "./update.js";
import {
compareSemVer,
isNewerVersion,
matchAssetForPlatform,
normalizeRepo,
isValidRepo,
type GitHubAsset,
} from "./update.js";
describe("update version comparator", () => {
test("correctly identifies newer semantic versions", () => {
@@ -20,6 +27,29 @@ describe("update version comparator", () => {
});
});
describe("normalizeRepo and isValidRepo", () => {
test("normalizeRepo trims and cleans various GitHub URL formats", () => {
expect(normalizeRepo("yunyingk/hose-use")).toBe("yunyingk/hose-use");
expect(normalizeRepo("https://github.com/yunyingk/hose-use")).toBe("yunyingk/hose-use");
expect(normalizeRepo("https://github.com/yunyingk/hose-use.git")).toBe("yunyingk/hose-use");
expect(normalizeRepo("http://www.github.com/my-org/my-fork/")).toBe("my-org/my-fork");
expect(normalizeRepo(" custom/project.git ")).toBe("custom/project");
expect(normalizeRepo("github.com/test-org/repo")).toBe("test-org/repo");
});
test("isValidRepo validates owner/repo format and rejects illegal inputs", () => {
expect(isValidRepo("yunyingk/hose-use")).toBe(true);
expect(isValidRepo("my-org/hose-use-fork")).toBe(true);
expect(isValidRepo("user.name/repo_name.v2")).toBe(true);
expect(isValidRepo("")).toBe(false);
expect(isValidRepo("single-word")).toBe(false);
expect(isValidRepo("too/many/parts/here")).toBe(false);
expect(isValidRepo("../path/traversal")).toBe(false);
expect(isValidRepo("invalid character/repo")).toBe(false);
});
});
describe("matchAssetForPlatform", () => {
const assets: GitHubAsset[] = [
{ name: "hose-use-darwin-arm64", downloadUrl: "https://example.com/darwin-arm64", size: 100 },
@@ -49,3 +79,4 @@ describe("matchAssetForPlatform", () => {
expect(matched?.name).toBe("hose-use-windows-x64.zip");
});
});
+158 -42
View File
@@ -3,6 +3,7 @@ import { dirname, join } from "node:path";
import { spawnSync } from "node:child_process";
import { isCompiledBinary, resolveAppRoot } from "../../core/runtime.js";
import { syncGlobalSkillIfPresent } from "../../core/embedded-skill.js";
import { loadGlobalConfig } from "../../core/config/loader.js";
import { VERSION } from "../../version.js";
import { booleanOption, numberOption, stringOption } from "../parser.js";
import { printJson, printKeyValue } from "../printer.js";
@@ -11,15 +12,29 @@ import type { CliParsedArgs, CliResult, CliRunOptions, CliRuntime } from "../typ
const DEFAULT_GITHUB_REPO = "yunyingk/hose-use";
const GITHUB_REPO_ENV = "HOSE_USE_GITHUB_REPO";
export type UpdateSourcePreference = "auto" | "github" | "gitea";
export type UpdateOptions = {
checkOnly?: boolean;
changelogOnly?: boolean;
limit?: number;
force?: boolean;
targetVersion?: string;
repo?: string;
repo: string;
sourcePreference: UpdateSourcePreference;
};
export function normalizeRepo(raw: string): string {
let repo = raw.trim();
repo = repo.replace(/^(https?:\/\/)?(www\.)?github\.com\//i, "");
repo = repo.replace(/\.git$/i, "").replace(/\/+$/, "");
return repo;
}
export function isValidRepo(repo: string): boolean {
return /^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/.test(repo);
}
export async function handleUpdateCommand(
parsed: CliParsedArgs,
runtime: CliRuntime,
@@ -47,11 +62,44 @@ export async function handleUpdateCommand(
? targetVersionRaw.replace(/^v/, "")
: undefined;
const repo =
const isGitHub = booleanOption(parsed.options, ["github", "gh"]);
const isGitea = booleanOption(parsed.options, ["gitea", "yingqing", "mirror"]);
const globalConfig = loadGlobalConfig();
const configuredSource = globalConfig.updateSource || "auto";
let sourcePreference: UpdateSourcePreference = "auto";
if (isGitHub) {
sourcePreference = "github";
} else if (isGitea) {
sourcePreference = "gitea";
} else if (configuredSource === "github" || configuredSource === "gitea") {
sourcePreference = configuredSource;
}
const rawRepo =
stringOption(parsed.options, ["repo"]) ||
process.env[GITHUB_REPO_ENV]?.trim() ||
globalConfig.updateRepo?.trim() ||
DEFAULT_GITHUB_REPO;
const repo = normalizeRepo(rawRepo);
if (!isValidRepo(repo)) {
const errorMsg = `非法 GitHub 仓库标识: '${rawRepo}'。应为 'owner/repo' 格式(如 'yunyingk/hose-use')。`;
if (runtime.jsonMode) {
return {
stdout: printJson({ updated: false, error: true, message: errorMsg }),
stderr: "",
exitCode: 1,
};
}
return {
stdout: "",
stderr: `[ERROR] ${errorMsg}\n`,
exitCode: 1,
};
}
const options: UpdateOptions = {
checkOnly: isCheck,
changelogOnly: isChangelog,
@@ -59,6 +107,7 @@ export async function handleUpdateCommand(
force: booleanOption(parsed.options, ["force", "f"]),
targetVersion,
repo,
sourcePreference,
};
const appRoot = runOptions.appRoot || resolveAppRoot(runOptions.entryFile);
@@ -112,11 +161,13 @@ export async function handleUpdateCommand(
// 1. Changelog / Release History query
if (options.changelogOnly) {
const releases = await fetchGitHubReleases(repo, options.limit ?? 10);
const releases = await fetchGitHubReleases(repo, options.limit ?? 10, options.sourcePreference);
if (runtime.jsonMode) {
return {
stdout: printJson({
currentVersion: VERSION,
repo,
sourcePreference: options.sourcePreference,
totalQueried: releases.length,
releases: releases.map((r) => ({
version: r.version,
@@ -157,7 +208,7 @@ export async function handleUpdateCommand(
// 2. Source development mode (running via bun/node)
if (!isCompiledBinary()) {
if (options.checkOnly) {
const releases = await fetchGitHubReleases(repo, 30);
const releases = await fetchGitHubReleases(repo, 30, options.sourcePreference);
const latestRelease = releases[0];
const latestVersion = latestRelease?.version ?? VERSION;
const currentRelease = releases.find((r) => r.version === VERSION);
@@ -174,6 +225,8 @@ export async function handleUpdateCommand(
latestVersion,
latestVersionPublishedAt: latestRelease?.publishedAt,
behindCount: pendingReleases.length,
repo,
sourcePreference: options.sourcePreference,
pendingReleases: pendingReleases.map((r) => ({
version: r.version,
tagName: r.tagName,
@@ -197,6 +250,8 @@ export async function handleUpdateCommand(
"当前版本": `v${VERSION}`,
"最新版本": `v${latestVersion} ${isUpgrade ? "(可升级 ✨)" : "(已是最新 ✅)"}`,
"待更新版本数": pendingReleases.length,
"发布仓库": repo,
"通道偏好": options.sourcePreference,
"源码路径": appRoot,
});
@@ -241,11 +296,11 @@ export async function handleUpdateCommand(
const platform = detectPlatform();
const arch = detectArch();
const releases = await fetchGitHubReleases(repo, 30);
const releases = await fetchGitHubReleases(repo, 30, options.sourcePreference);
const release = targetVersion
? (releases.find((r) => r.version === targetVersion || r.tagName === targetVersion || r.tagName === `v${targetVersion}`) ??
await fetchGitHubRelease(repo, targetVersion))
: (releases[0] ?? await fetchGitHubRelease(repo));
await fetchGitHubRelease(repo, targetVersion, options.sourcePreference))
: (releases[0] ?? await fetchGitHubRelease(repo, undefined, options.sourcePreference));
if (!release) {
const errorMsg = `无法从 GitHub 仓库 '${repo}' 获取 Release 列表`;
@@ -254,6 +309,8 @@ export async function handleUpdateCommand(
stdout: printJson({
updated: false,
currentVersion: VERSION,
repo,
sourcePreference: options.sourcePreference,
mode: "binary",
message: errorMsg,
}),
@@ -285,6 +342,8 @@ export async function handleUpdateCommand(
latestVersion,
latestVersionPublishedAt: release.publishedAt,
behindCount: pendingReleases.length,
repo,
sourcePreference: options.sourcePreference,
pendingReleases: pendingReleases.map((r) => ({
version: r.version,
tagName: r.tagName,
@@ -308,6 +367,8 @@ export async function handleUpdateCommand(
"最新版本": `v${latestVersion} ${isUpgrade ? "(可升级 ✨)" : "(已是最新 ✅)"}`,
"发布时间": release.publishedAt ? release.publishedAt.slice(0, 10) : "未知",
"平台架构": `${platform}-${arch}`,
"发布仓库": repo,
"通道偏好": options.sourcePreference,
});
return {
@@ -326,6 +387,8 @@ export async function handleUpdateCommand(
currentVersionPublishedAt: currentRelease?.publishedAt,
latestVersion,
latestVersionPublishedAt: release.publishedAt,
repo,
sourcePreference: options.sourcePreference,
mode: "binary",
message: `hose-use 当前已是最新版本 (v${VERSION})`,
}),
@@ -365,7 +428,7 @@ export async function handleUpdateCommand(
try {
const downloadedFile = join(tmpDir, asset.name);
await downloadFile(asset.downloadUrl, downloadedFile, release.tagName, asset.name);
await downloadFile(asset.downloadUrl, downloadedFile, release.tagName, asset.name, repo, options.sourcePreference);
let newBinaryPath = downloadedFile;
if (asset.name.endsWith(".tar.gz") || asset.name.endsWith(".tgz")) {
@@ -456,7 +519,11 @@ export type GitHubRelease = {
assets: GitHubAsset[];
};
export async function fetchGitHubReleases(repo: string, limit = 20): Promise<GitHubRelease[]> {
export async function fetchGitHubReleases(
repo: string,
limit = 20,
sourcePreference: UpdateSourcePreference = "auto"
): Promise<GitHubRelease[]> {
const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
const headers: Record<string, string> = {
"User-Agent": `hose-use/${VERSION}`,
@@ -464,10 +531,25 @@ export async function fetchGitHubReleases(repo: string, limit = 20): Promise<Git
...(token ? { Authorization: `Bearer ${token}` } : {}),
};
const urls = [
`https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases?per_page=${limit}`,
`https://api.github.com/repos/${repo}/releases?per_page=${limit}`,
];
const isDefaultRepo = repo.toLowerCase() === DEFAULT_GITHUB_REPO.toLowerCase();
const allowGitea = isDefaultRepo && sourcePreference !== "github";
const urls: string[] = [];
if (sourcePreference === "github") {
urls.push(`https://api.github.com/repos/${repo}/releases?per_page=${limit}`);
} else if (sourcePreference === "gitea") {
if (allowGitea) {
urls.push(`https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases?per_page=${limit}`);
}
urls.push(`https://api.github.com/repos/${repo}/releases?per_page=${limit}`);
} else {
if (allowGitea) {
urls.push(`https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases?per_page=${limit}`);
}
urls.push(`https://api.github.com/repos/${repo}/releases?per_page=${limit}`);
}
let fallbackList: GitHubRelease[] = [];
for (const url of urls) {
try {
@@ -506,18 +588,26 @@ export async function fetchGitHubReleases(repo: string, limit = 20): Promise<Git
assets,
});
}
if (list.length > 0) return list;
if (list.length > 0) {
if (list.some((r) => r.assets.length > 0)) {
return list;
}
if (fallbackList.length === 0) {
fallbackList = list;
}
}
} catch {
// try next source
}
}
return [];
return fallbackList;
}
export async function fetchGitHubRelease(
repo: string,
targetVersion?: string
targetVersion?: string,
sourcePreference: UpdateSourcePreference = "auto"
): Promise<GitHubRelease | undefined> {
const tag = targetVersion ? (targetVersion.startsWith("v") ? targetVersion : `v${targetVersion}`) : undefined;
const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
@@ -527,15 +617,26 @@ export async function fetchGitHubRelease(
...(token ? { Authorization: `Bearer ${token}` } : {}),
};
const urls = tag
? [
`https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases/tags/${tag}`,
`https://api.github.com/repos/${repo}/releases/tags/${tag}`,
]
: [
`https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases/latest`,
`https://api.github.com/repos/${repo}/releases/latest`,
];
const isDefaultRepo = repo.toLowerCase() === DEFAULT_GITHUB_REPO.toLowerCase();
const allowGitea = isDefaultRepo && sourcePreference !== "github";
const urls: string[] = [];
const giteaTagUrl = tag
? `https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases/tags/${tag}`
: `https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases/latest`;
const githubTagUrl = tag
? `https://api.github.com/repos/${repo}/releases/tags/${tag}`
: `https://api.github.com/repos/${repo}/releases/latest`;
if (sourcePreference === "github") {
urls.push(githubTagUrl);
} else if (sourcePreference === "gitea") {
if (allowGitea) urls.push(giteaTagUrl);
urls.push(githubTagUrl);
} else {
if (allowGitea) urls.push(giteaTagUrl);
urls.push(githubTagUrl);
}
let fallbackRelease: GitHubRelease | undefined;
@@ -642,32 +743,47 @@ function logProgress(msg: string) {
}
}
async function downloadFile(url: string, destPath: string, tagName?: string, assetName?: string) {
export async function downloadFile(
url: string,
destPath: string,
tagName?: string,
assetName?: string,
repo: string = DEFAULT_GITHUB_REPO,
sourcePreference: UpdateSourcePreference = "auto"
) {
const candidates: string[] = [];
const tag = tagName ? (tagName.startsWith("v") ? tagName : `v${tagName}`) : undefined;
const fileName = assetName || url.split("/").pop() || "";
const isDefaultRepo = repo.toLowerCase() === DEFAULT_GITHUB_REPO.toLowerCase();
const allowGitea = isDefaultRepo && sourcePreference !== "github";
// 1. High-speed Gitea direct mirror first
if (tag && fileName) {
candidates.push(`https://git.ying-qing.cn/gitea/hose-use/releases/download/${tag}/${fileName}`);
}
if (url.startsWith("https://git.ying-qing.cn")) {
candidates.push(url);
// 1. High-speed Gitea direct mirror first (only for default official repo)
if (allowGitea) {
if (tag && fileName) {
candidates.push(`https://git.ying-qing.cn/gitea/hose-use/releases/download/${tag}/${fileName}`);
}
if (url.startsWith("https://git.ying-qing.cn")) {
candidates.push(url);
}
}
// 2. Fast GitHub CDN proxies and direct GitHub fallback
// 2. Fast GitHub CDN proxies and direct GitHub fallback (dynamic repo)
if (tag && fileName) {
const ghDirectUrl = `https://github.com/${DEFAULT_GITHUB_REPO}/releases/download/${tag}/${fileName}`;
candidates.push(`https://ghfast.top/${ghDirectUrl}`);
candidates.push(`https://ghproxy.net/${ghDirectUrl}`);
candidates.push(`https://gh.ddlc.top/${ghDirectUrl}`);
candidates.push(`https://mirror.ghproxy.com/${ghDirectUrl}`);
const ghDirectUrl = `https://github.com/${repo}/releases/download/${tag}/${fileName}`;
if (sourcePreference !== "gitea") {
candidates.push(`https://ghfast.top/${ghDirectUrl}`);
candidates.push(`https://ghproxy.net/${ghDirectUrl}`);
candidates.push(`https://gh.ddlc.top/${ghDirectUrl}`);
candidates.push(`https://mirror.ghproxy.com/${ghDirectUrl}`);
}
candidates.push(ghDirectUrl);
} else if (url.includes("github.com")) {
candidates.push(`https://ghfast.top/${url}`);
candidates.push(`https://ghproxy.net/${url}`);
candidates.push(`https://gh.ddlc.top/${url}`);
candidates.push(`https://mirror.ghproxy.com/${url}`);
if (sourcePreference !== "gitea") {
candidates.push(`https://ghfast.top/${url}`);
candidates.push(`https://ghproxy.net/${url}`);
candidates.push(`https://gh.ddlc.top/${url}`);
candidates.push(`https://mirror.ghproxy.com/${url}`);
}
candidates.push(url);
} else {
candidates.push(url);
+4 -1
View File
@@ -127,9 +127,11 @@ export function printHelp(): string {
dimension 系统/自定义档案维度 (list, items <维度>)
role 角色定义与成员 (list, groups, members <角色>)
permission 权限模型快照 (get)
rule 本地 AI 审批规约管理 (scopes, scope <索引号|场景>, list, get, add, delete)
approval 确定性审批网关与要点仲裁 (audit points <单号>, checklist <单号>, review <单号>, decide <单号>)
skill Agent Skill 管理 (install, status, dump)
probe 连通性诊断 (probe [corpId])
update 版本自更新与发布记录 (update, update check, update --changelog)
update 版本自更新与发布记录 (update, update check, update --changelog, --github, --gitea, --repo=<owner/repo>)
openapi OpenAPI 3.1.0 规范导出 (openapi, openapi --raw, openapi paths, openapi info)
http 启动轻量 HTTP Server 与交互式文档 (http [--port=8888] [--host=127.0.0.1])
service 常驻守护进程管理 (service start|stop|restart|status|logs|poll)
@@ -194,6 +196,7 @@ export function printHelp(): string {
hose-use probe # 诊断当前企业鉴权连通性
hose-use skill install # 安装 Agent 技能到用户目录
hose-use update # 自动检查并升级到最新版本
hose-use update --github # 强制走官方 GitHub 源升级
hose-use update --changelog # 查看版本发布历史
hose-use openapi paths # 查看所有 API 路径与概要一览
hose-use openapi --raw # 导出原生下游全量 OpenAPI 规范
+9
View File
@@ -21,6 +21,8 @@ import { handleMessageCommand } from "./commands/message.js";
import { handleDimensionCommand } from "./commands/dimension.js";
import { handleRoleCommand } from "./commands/role.js";
import { handlePermissionCommand } from "./commands/permission.js";
import { handleRuleCommand } from "./commands/rule.js";
import { handleApprovalCommand } from "./commands/approval.js";
import type { CliParsedArgs, CliResult, CliRunOptions } from "./types.js";
const STANDING_COMMANDS = new Set(["http", "server", "web", "mcp"]);
@@ -181,6 +183,13 @@ async function dispatchCli(
case "permission":
case "permissions":
return await handlePermissionCommand(parsed, runtime);
case "rule":
case "rules":
return await handleRuleCommand(parsed, runtime);
case "approval":
case "approvals":
case "audit":
return await handleApprovalCommand(parsed, runtime);
case "message":
case "messages":
case "notify":
+1 -5
View File
@@ -86,11 +86,7 @@ export function loadGlobalConfig(): GlobalConfig {
// 容错返回默认
}
return {
stateful: true,
defaultCorpId: undefined,
defaultAccountId: undefined,
};
return GlobalConfigSchema.parse({});
}
export function saveGlobalConfig(config: Partial<GlobalConfig>): GlobalConfig {
+3
View File
@@ -65,6 +65,9 @@ export const GlobalConfigSchema = z.object({
stateful: z.boolean().default(true).describe("是否为有状态模式 (true 记忆默认企业,false 无状态需显式传 --corp)"),
defaultCorpId: z.string().optional().describe("默认工作企业 ID"),
defaultAccountId: z.string().optional().describe("默认主账号"),
updateRepo: z.string().optional().describe("默认自更新的 GitHub 仓库 (owner/repo)"),
updateSource: z.enum(["auto", "github", "gitea"]).optional().default("auto").describe("默认自更新源通道偏好 (auto/github/gitea)"),
});
export type GlobalConfig = z.infer<typeof GlobalConfigSchema>;
+252
View File
@@ -0,0 +1,252 @@
import { Database } from "bun:sqlite";
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { closeApprovalDatabase, getApprovalDatabase } from "./db.js";
import { ApprovalRepository } from "./repository.js";
import { ApprovalRuleValidationError } from "./types.js";
describe("Approval Domain - SQLite 持久化与规约仓储", () => {
let db: Database;
let repo: ApprovalRepository;
beforeEach(() => {
// 每次测试使用独立的内存数据库,隔离状态
db = getApprovalDatabase(":memory:");
repo = new ApprovalRepository(db);
});
afterEach(() => {
closeApprovalDatabase();
});
test("数据库初始化时自动种子化默认偏好配置", () => {
const defaultPref = repo.getDefaultPreference();
expect(defaultPref).toBeDefined();
expect(defaultPref.id).toBe("default");
expect(defaultPref.name).toBe("标准财务审批偏好");
expect(defaultPref.rulesReject).toContain("@{硬性}");
expect(defaultPref.rulesReview).toContain("@{特殊}");
});
test("成功创建合规规则并自动递增编号", () => {
const rule1 = repo.createRule({
scope: "差旅报销",
body: "差旅报销时,[一定需要上传发票]{硬性},[尽量上传支付凭证]{弹性}。"
});
expect(rule1.id).toBeDefined();
expect(rule1.code).toBe(1);
expect(rule1.scope).toBe("差旅报销");
expect(rule1.version).toBe(1);
expect(rule1.status).toBe("active");
const rule2 = repo.createRule({
scope: "业务招待",
body: "招待报销时,[必须提供菜单水单]{硬性};[建议注明客户姓名与职务]{建议}。"
});
expect(rule2.code).toBe(2);
expect(rule2.scope).toBe("业务招待");
expect(repo.countRules()).toBe(2);
});
test("强校验拦截:不合规的规则正文物理禁止入库", () => {
const initialCount = repo.countRules();
expect(() => {
repo.createRule({
scope: "差旅报销",
body: "差旅报销时,[必须上传发票]{严重}。" // 非法严格程度
});
}).toThrow(ApprovalRuleValidationError);
// 验证数据库没有任何脏数据写入
expect(repo.countRules()).toBe(initialCount);
expect(() => {
repo.createRule({
scope: "差旅报销",
body: "差旅报销时,[必须上传发票],大家遵守。" // 悬空中括号
});
}).toThrow(ApprovalRuleValidationError);
expect(repo.countRules()).toBe(initialCount);
});
test("更新规则正文时自动增加版本号并再次校验", () => {
const created = repo.createRule({
scope: "差旅报销",
body: "差旅报销时,[必须上传发票]{硬性}。"
});
expect(created.version).toBe(1);
// 正常更新
const updated = repo.updateRule(created.id, {
body: "差旅报销时,[必须上传发票]{硬性};[尽量上传水单]{弹性}。"
});
expect(updated.version).toBe(2);
expect(updated.body).toContain("[尽量上传水单]{弹性}");
// 非法更新被拦截,原数据不变
expect(() => {
repo.updateRule(created.id, {
body: "差旅报销时,[必须上传发票]{未知名词}。"
});
}).toThrow(ApprovalRuleValidationError);
const check = repo.getRuleById(created.id);
expect(check?.version).toBe(2); // 版本未递增,未被篡改
});
test("按 Scope 与 Status 进行条件过滤检索", () => {
repo.createRule({
scope: "差旅报销",
body: "[必须提供发票]{硬性}。"
});
repo.createRule({
scope: "差旅报销",
body: "[尽量提供水单]{弹性}。",
status: "draft"
});
repo.createRule({
scope: "业务招待",
body: "[必须提供人均名单]{硬性}。"
});
const travelRules = repo.listRules({ scope: "差旅报销" });
expect(travelRules.length).toBe(2);
const activeTravelRules = repo.listRules({ scope: "差旅报销", status: "active" });
expect(activeTravelRules.length).toBe(1);
const entertainRules = repo.listRules({ scope: "业务招待" });
expect(entertainRules.length).toBe(1);
});
test("一键获取去重索引列表 listScopes 及对应的索引编号", () => {
// 插入多条规则,部分共享相同索引
repo.createRule({ scope: "差旅报销", body: "[必须上传发票]{硬性}。" });
repo.createRule({ scope: "差旅报销", body: "[尽量上传水单]{弹性}。" });
repo.createRule({ scope: "业务招待", body: "[必须提供人均名单]{硬性}。" });
repo.createRule({ scope: "差旅报销", body: "[建议注明事由]{建议}。" });
repo.createRule({ scope: "办公采购", body: "[发票抬头须一致]{硬性}。" });
const scopes = repo.listScopes("active");
expect(scopes.length).toBe(3); // 差旅报销、业务招待、办公采购
// 验证索引 1:差旅报销
expect(scopes[0]!.index).toBe(1);
expect(scopes[0]!.scope).toBe("差旅报销");
expect(scopes[0]!.ruleCount).toBe(3);
expect(scopes[0]!.ruleCodes).toEqual([1, 2, 4]);
// 验证索引 2:业务招待
expect(scopes[1]!.index).toBe(2);
expect(scopes[1]!.scope).toBe("业务招待");
expect(scopes[1]!.ruleCount).toBe(1);
expect(scopes[1]!.ruleCodes).toEqual([3]);
// 验证索引 3:办公采购
expect(scopes[2]!.index).toBe(3);
expect(scopes[2]!.scope).toBe("办公采购");
expect(scopes[2]!.ruleCount).toBe(1);
expect(scopes[2]!.ruleCodes).toEqual([5]);
});
test("通过索引编号或索引名称获取该索引对应的所有规则明细 getScopeDetail", () => {
repo.createRule({ scope: "差旅报销", body: "[必须上传发票]{硬性}。" });
repo.createRule({ scope: "差旅报销", body: "[尽量上传支付凭证]{弹性}。" });
repo.createRule({ scope: "业务招待", body: "[必须提供人均名单]{硬性}。" });
// 1. 通过数字索引号 1 检索
const detailByIndex = repo.getScopeDetail(1);
expect(detailByIndex).not.toBeNull();
expect(detailByIndex!.scope).toBe("差旅报销");
expect(detailByIndex!.rules.length).toBe(2);
expect(detailByIndex!.rules[0]!.parsed.clauses[0]!.strictness).toBe("硬性");
expect(detailByIndex!.rules[1]!.parsed.clauses[0]!.strictness).toBe("弹性");
// 2. 通过索引名称 "业务招待" 检索
const detailByName = repo.getScopeDetail("业务招待");
expect(detailByName).not.toBeNull();
expect(detailByName!.index).toBe(2);
expect(detailByName!.rules.length).toBe(1);
// 3. 不存在的索引号返回 null
expect(repo.getScopeDetail(999)).toBeNull();
expect(repo.getScopeDetail("不存在的场景")).toBeNull();
});
test("风格偏好的更新与非法引用拦截", () => {
const pref = repo.getDefaultPreference();
const updated = repo.updatePreference(pref.id, {
name: "宽松型偏好",
rulesReview: "触发 @{特殊} 条款;未满足 @{弹性} 且金额 > 2000 元"
});
expect(updated.name).toBe("宽松型偏好");
expect(updated.rulesReview).toContain("金额 > 2000 元");
// 非法偏好引用被拦截
expect(() => {
repo.updatePreference(pref.id, {
rulesReview: "触犯 @{严重} 条款则复核"
});
}).toThrow(ApprovalRuleValidationError);
});
test("审批运行、要点清单注入与全流程审计流水登记", () => {
// 1. 创建审批运行记录并注入要点清单
const run = repo.createOrResetApprovalRun({
documentSn: "TEST260001",
flowId: "FLOW_001",
decision: "PENDING",
});
expect(run.id).toBeDefined();
expect(run.documentSn).toBe("TEST260001");
expect(run.decision).toBe("PENDING");
const findings = repo.injectFindings(run.id, [
{ clauseText: "必须上传发票", strictness: "硬性", checkStatus: "PENDING" },
{ clauseText: "建议说明事由", strictness: "建议", checkStatus: "PENDING" },
]);
expect(findings.length).toBe(2);
expect(findings[0]!.strictness).toBe("硬性");
expect(findings[0]!.checkStatus).toBe("PENDING");
// 2. 更新核验状态
const updated = repo.updateFinding(findings[0]!.id, {
checkStatus: "FAIL",
evidence: "未提供发票附件",
});
expect(updated.checkStatus).toBe("FAIL");
expect(updated.evidence).toBe("未提供发票附件");
// 3. 登记 AI PRO 审计监控日志
const log = repo.logAiProAction({
action: "decide",
documentSn: "TEST260001",
operator: "AI-Agent-01",
status: "BLOCKED",
decision: "REJECT",
summary: "硬性违规条款未通过,网关阻断放行",
});
expect(log.id).toBeDefined();
expect(log.status).toBe("BLOCKED");
const logs = repo.listAiProLogs("TEST260001");
expect(logs.length).toBe(1);
expect(logs[0]!.action).toBe("decide");
expect(logs[0]!.status).toBe("BLOCKED");
});
});
+177
View File
@@ -0,0 +1,177 @@
import { Database } from "bun:sqlite";
import { existsSync, mkdirSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
export const DEFAULT_APPROVAL_DB_PATH = join(
homedir(),
".config",
"hose-use",
"approval.db"
);
export function resolveApprovalDbPath(): string {
const envPath = process.env.HOSE_APPROVAL_DB?.trim();
if (envPath) {
return envPath;
}
return DEFAULT_APPROVAL_DB_PATH;
}
let activeDb: Database | null = null;
let currentDbPath: string | null = null;
/**
* 获取或创建 SQLite 数据库连接单例
*/
export function getApprovalDatabase(customPath?: string): Database {
const targetPath = customPath ?? resolveApprovalDbPath();
if (activeDb && currentDbPath === targetPath) {
return activeDb;
}
// 内存数据库无需创建目录
if (targetPath !== ":memory:") {
const dir = dirname(targetPath);
if (!existsSync(dir)) {
mkdirSync(dir, { recursive: true, mode: 0o700 });
}
}
const db = new Database(targetPath);
currentDbPath = targetPath;
activeDb = db;
initDatabaseSchema(db);
return db;
}
/**
* 关闭并清理当前数据库连接(用于测试重置或进程退出)
*/
export function closeApprovalDatabase(): void {
if (activeDb) {
activeDb.close();
activeDb = null;
currentDbPath = null;
}
}
/**
* 初始化表结构与默认数据
*/
export function initDatabaseSchema(db: Database): void {
// 启用 WAL 模式提高并发性能与数据安全性
db.run("PRAGMA journal_mode = WAL;");
db.run("PRAGMA foreign_keys = ON;");
// 1. 规约主表
db.run(`
CREATE TABLE IF NOT EXISTS rules (
id TEXT PRIMARY KEY,
code INTEGER NOT NULL UNIQUE,
scope TEXT NOT NULL,
body TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'active',
version INTEGER NOT NULL DEFAULT 1,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
`);
db.run("CREATE INDEX IF NOT EXISTS idx_rules_scope ON rules(scope);");
db.run("CREATE INDEX IF NOT EXISTS idx_rules_status ON rules(status);");
// 2. 风格偏好表
db.run(`
CREATE TABLE IF NOT EXISTS preferences (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
is_default INTEGER NOT NULL DEFAULT 0,
rules_reject TEXT NOT NULL,
rules_review TEXT NOT NULL,
rules_pass_note TEXT NOT NULL,
rules_approve TEXT NOT NULL,
updated_at INTEGER NOT NULL
);
`);
// 3. 审批运行执行记录表
db.run(`
CREATE TABLE IF NOT EXISTS approval_runs (
id TEXT PRIMARY KEY,
flow_id TEXT,
document_sn TEXT NOT NULL,
corp_id TEXT,
decision TEXT NOT NULL,
decision_summary TEXT,
matched_rules_count INTEGER NOT NULL DEFAULT 0,
failed_rules_count INTEGER NOT NULL DEFAULT 0,
document_snapshot TEXT,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
`);
db.run("CREATE INDEX IF NOT EXISTS idx_runs_document_sn ON approval_runs(document_sn);");
db.run("CREATE INDEX IF NOT EXISTS idx_runs_created_at ON approval_runs(created_at);");
// 4. 审批要点事实记录表
db.run(`
CREATE TABLE IF NOT EXISTS approval_findings (
id TEXT PRIMARY KEY,
run_id TEXT NOT NULL REFERENCES approval_runs(id) ON DELETE CASCADE,
rule_id TEXT REFERENCES rules(id) ON DELETE SET NULL,
clause_text TEXT NOT NULL,
strictness TEXT NOT NULL,
check_status TEXT NOT NULL,
evidence TEXT,
reasoning TEXT,
created_at INTEGER NOT NULL
);
`);
db.run("CREATE INDEX IF NOT EXISTS idx_findings_run_id ON approval_findings(run_id);");
// 5. AI PRO 全流程操作与审计监控流水表
db.run(`
CREATE TABLE IF NOT EXISTS aipro_logs (
id TEXT PRIMARY KEY,
action TEXT NOT NULL,
document_sn TEXT,
operator TEXT,
args TEXT,
status TEXT NOT NULL,
decision TEXT,
summary TEXT,
created_at INTEGER NOT NULL
);
`);
db.run("CREATE INDEX IF NOT EXISTS idx_aipro_logs_document_sn ON aipro_logs(document_sn);");
db.run("CREATE INDEX IF NOT EXISTS idx_aipro_logs_created_at ON aipro_logs(created_at);");
// 种子数据:初始化默认偏好
seedDefaultPreference(db);
}
function seedDefaultPreference(db: Database): void {
const existing = db.query("SELECT id FROM preferences WHERE id = 'default'").get();
if (!existing) {
const now = Date.now();
db.run(
`
INSERT INTO preferences (
id, name, is_default, rules_reject, rules_review, rules_pass_note, rules_approve, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
`,
[
"default",
"标准财务审批偏好",
1,
"确认触犯任何 @{硬性} 条款(刚性底线,直接阻断)",
"触发任何 @{特殊} 条款;未满足 @{弹性} 条款且单据金额 > 500 元;未满足 @{弹性} 累计达 3 处以上;单据未命中任何已有规则",
"未满足 @{弹性} 条款但单据金额 <= 500 元(企业尺度豁免放行);未满足 @{建议} 条款(倡导性要求,附温馨提示)",
"所有条款全部满足,秒级免审全自动通过",
now
]
);
}
}
+5
View File
@@ -0,0 +1,5 @@
export * from "./types.js";
export * from "./parser.js";
export * from "./db.js";
export * from "./repository.js";
export * from "./service.js";
+84
View File
@@ -0,0 +1,84 @@
import { describe, expect, test } from "bun:test";
import { parseRuleBody, validatePreferenceText } from "./parser.js";
import { ApprovalRuleValidationError } from "./types.js";
describe("Approval Rule Parser - 规则语法解析与校验", () => {
test("正常解析包含单一硬性条款的规则", () => {
const text = "差旅报销时,[必须上传真实有效的发票]{硬性}。";
const result = parseRuleBody(text);
expect(result.clauses.length).toBe(1);
expect(result.clauses[0]!.action).toBe("必须上传真实有效的发票");
expect(result.clauses[0]!.strictness).toBe("硬性");
expect(result.cleanText).toBe("差旅报销时,必须上传真实有效的发票。");
});
test("正常解析包含复合梯度(硬性、弹性、建议、特殊)的整段自然语言规约", () => {
const text =
"员工进行差旅报销时,[一定需要上传发票]{硬性}。[尽量上传支付凭证]{弹性}以佐证真实性;" +
"如涉及大额费用或合规争议,[须提交法务专项审核]{特殊};针对市内同城交通,[建议补充说明消费事由]{建议}。";
const result = parseRuleBody(text);
expect(result.clauses.length).toBe(4);
expect(result.clauses[0]!.action).toBe("一定需要上传发票");
expect(result.clauses[0]!.strictness).toBe("硬性");
expect(result.clauses[1]!.action).toBe("尽量上传支付凭证");
expect(result.clauses[1]!.strictness).toBe("弹性");
expect(result.clauses[2]!.action).toBe("须提交法务专项审核");
expect(result.clauses[2]!.strictness).toBe("特殊");
expect(result.clauses[3]!.action).toBe("建议补充说明消费事由");
expect(result.clauses[3]!.strictness).toBe("建议");
expect(result.cleanText).toBe(
"员工进行差旅报销时,一定需要上传发票。尽量上传支付凭证以佐证真实性;" +
"如涉及大额费用或合规争议,须提交法务专项审核;针对市内同城交通,建议补充说明消费事由。"
);
});
test("拦截非法的严格程度标签", () => {
const text = "差旅报销时,[必须上传发票]{必须遵守}。";
expect(() => parseRuleBody(text)).toThrow(ApprovalRuleValidationError);
expect(() => parseRuleBody(text)).toThrow('非法严格程度 "必须遵守"');
});
test("拦截悬空的中括号(未指定严格程度)", () => {
const text = "差旅报销时,[必须上传发票],请大家注意。";
expect(() => parseRuleBody(text)).toThrow(ApprovalRuleValidationError);
expect(() => parseRuleBody(text)).toThrow('检测到未指定严格程度的标记 "[必须上传发票]"');
});
test("拦截括号未闭合的语法错误", () => {
expect(() => parseRuleBody("差旅报销时,[必须上传发票{硬性}。")).toThrow("未闭合的左中括号");
expect(() => parseRuleBody("差旅报销时,[必须上传发票]{硬性。")).toThrow("未闭合的左花括号");
expect(() => parseRuleBody("差旅报销时,必须上传发票]{硬性}。")).toThrow("未匹配的多余右中括号");
});
test("拦截空的动作句式", () => {
const text = "差旅报销时,[ ]{硬性}。";
expect(() => parseRuleBody(text)).toThrow(ApprovalRuleValidationError);
expect(() => parseRuleBody(text)).toThrow("动作句式不能为空");
});
test("拦截未包含任何判定标记的纯文字", () => {
const text = "这是一段关于差旅报销的日常说明,没有任何裁判条款。";
expect(() => parseRuleBody(text)).toThrow(ApprovalRuleValidationError);
expect(() => parseRuleBody(text)).toThrow("未包含任何有效的规则标记");
});
});
describe("Approval Preference Parser - 偏好引用语法校验", () => {
test("校验通过合法的 @{级别} 引用", () => {
const text = "满足以下条件:触犯任何 @{硬性} 条款,或触发 @{特殊} 条款,或未满足 @{弹性} 且金额 > 500";
expect(validatePreferenceText(text)).toBe(true);
});
test("拦截非法的 @{级别} 引用", () => {
const text = "若违反 @{严重} 条款则驳回";
expect(() => validatePreferenceText(text)).toThrow(ApprovalRuleValidationError);
expect(() => validatePreferenceText(text)).toThrow('非法的偏好引用 "@{严重}"');
});
});
+149
View File
@@ -0,0 +1,149 @@
import {
ApprovalRuleValidationError,
isValidStrictnessTier,
ParsedRule,
RuleClause,
StrictnessTier,
VALID_STRICTNESS_TIERS
} from "./types.js";
const CLAUSE_REGEX = /\[([^\[\]]+)\]\{([^{}]+)\}/g;
const ORPHAN_BRACKET_REGEX = /\[([^\[\]]+)\](?!\s*\{)/g;
const PREFERENCE_REF_REGEX = /@\{([^{}]+)\}/g;
/**
* 解析并严格校验规则正文
*
* 规则正文格式:
* 采用自然语言,在需要约束的判定点使用 [动作句式]{严格程度} 包裹。
* 允许的严格程度:硬性 | 弹性 | 建议 | 特殊
*
* @throws {ApprovalRuleValidationError} 当语法不合规或严格程度非法时抛出
*/
export function parseRuleBody(body: string): ParsedRule {
if (!body || typeof body !== "string" || body.trim().length === 0) {
throw new ApprovalRuleValidationError("规则正文不能为空");
}
// 1. 括号闭合完整性检查
checkBracketBalance(body);
// 2. 检测悬空的中括号(即写了 [动作] 但漏掉了 {级别})
const orphanMatches = Array.from(body.matchAll(ORPHAN_BRACKET_REGEX));
if (orphanMatches.length > 0) {
const firstOrphan = orphanMatches[0]![0];
throw new ApprovalRuleValidationError(
`检测到未指定严格程度的标记 "${firstOrphan}",请紧跟花括号指定级别,如 "${firstOrphan}{硬性}"`
);
}
// 3. 提取所有 [动作句式]{级别}
const clauses: RuleClause[] = [];
const matches = Array.from(body.matchAll(CLAUSE_REGEX));
for (const match of matches) {
const raw = match[0];
const rawAction = match[1];
const rawTier = match[2];
const startIndex = match.index ?? 0;
const endIndex = startIndex + raw.length;
const action = rawAction ? rawAction.trim() : "";
const tier = rawTier ? rawTier.trim() : "";
if (action.length === 0) {
throw new ApprovalRuleValidationError(`动作句式不能为空: "${raw}"`);
}
if (!isValidStrictnessTier(tier)) {
throw new ApprovalRuleValidationError(
`非法严格程度 "${tier}",仅支持:${VALID_STRICTNESS_TIERS.join("、")}`
);
}
clauses.push({
action,
strictness: tier as StrictnessTier,
raw,
startIndex,
endIndex
});
}
// 4. 一条合法的业务规约必须至少包含一个裁决要点
if (clauses.length === 0) {
throw new ApprovalRuleValidationError(
`规则正文未包含任何有效的规则标记,格式须为 [动作句式]{${VALID_STRICTNESS_TIERS.join("|")}}`
);
}
// 5. 生成剥离语法标记后的纯净自然语言
const cleanText = body.replace(CLAUSE_REGEX, (_match, action) => action.trim());
return {
rawBody: body,
clauses,
cleanText
};
}
/**
* 校验规则正文,合规返回 true,不合规抛出 ApprovalRuleValidationError
*/
export function validateRuleBody(body: string): boolean {
parseRuleBody(body);
return true;
}
/**
* 解析并校验偏好配置文本中的 @{级别} 引用
*/
export function validatePreferenceText(text: string): boolean {
if (!text || typeof text !== "string") return true;
const matches = Array.from(text.matchAll(PREFERENCE_REF_REGEX));
for (const match of matches) {
const tier = match[1]?.trim() ?? "";
if (!isValidStrictnessTier(tier)) {
throw new ApprovalRuleValidationError(
`非法的偏好引用 "@{${tier}}",仅支持:${VALID_STRICTNESS_TIERS.map((t) => `@{${t}}`).join("、")}`
);
}
}
return true;
}
/**
* 括号成对匹配与平衡检查
*/
function checkBracketBalance(text: string): void {
let openSquare = 0;
let openCurly = 0;
for (let i = 0; i < text.length; i++) {
const char = text[i];
if (char === "[") {
openSquare++;
} else if (char === "]") {
openSquare--;
if (openSquare < 0) {
throw new ApprovalRuleValidationError("检测到未匹配的多余右中括号 ']'");
}
} else if (char === "{") {
openCurly++;
} else if (char === "}") {
openCurly--;
if (openCurly < 0) {
throw new ApprovalRuleValidationError("检测到未匹配的多余右花括号 '}'");
}
}
}
if (openSquare > 0) {
throw new ApprovalRuleValidationError("检测到未闭合的左中括号 '['");
}
if (openCurly > 0) {
throw new ApprovalRuleValidationError("检测到未闭合的左花括号 '{'");
}
}
+635
View File
@@ -0,0 +1,635 @@
import { Database } from "bun:sqlite";
import { getApprovalDatabase } from "./db.js";
import { parseRuleBody, validatePreferenceText } from "./parser.js";
import {
AiProLogRecord,
ApprovalDecision,
ApprovalFindingRecord,
ApprovalRunRecord,
FindingCheckStatus,
PreferenceRecord,
RuleRecord,
ScopeDetail,
ScopeSummary,
StrictnessTier
} from "./types.js";
export interface CreateRuleInput {
scope: string;
body: string;
status?: "active" | "draft" | "archived";
}
export interface UpdateRuleInput {
scope?: string;
body?: string;
status?: "active" | "draft" | "archived";
}
export interface ListRulesFilter {
scope?: string;
status?: "active" | "draft" | "archived";
}
export class ApprovalRepository {
private db: Database;
constructor(db?: Database) {
this.db = db ?? getApprovalDatabase();
}
// ===================== 规约管理 (Rules) =====================
/**
* 创建规则:必须先通过语法校验器,校验通过方可入库
*/
public createRule(input: CreateRuleInput): RuleRecord {
// 语法强校验拦截:不合规直接抛错,物理阻止入库
parseRuleBody(input.body);
const now = Date.now();
const id = crypto.randomUUID();
// 自动分配自增可读编号 code
const maxCodeRow = this.db
.query("SELECT COALESCE(MAX(code), 0) AS maxCode FROM rules")
.get() as { maxCode: number } | null;
const nextCode = (maxCodeRow?.maxCode ?? 0) + 1;
const status = input.status ?? "active";
this.db.run(
`
INSERT INTO rules (id, code, scope, body, status, version, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, 1, ?, ?)
`,
[id, nextCode, input.scope.trim(), input.body.trim(), status, now, now]
);
return this.getRuleById(id)!;
}
public getRuleById(id: string): RuleRecord | null {
const row = this.db.query("SELECT * FROM rules WHERE id = ?").get(id) as any;
return row ? this.mapRuleRow(row) : null;
}
public getRuleByCode(code: number): RuleRecord | null {
const row = this.db.query("SELECT * FROM rules WHERE code = ?").get(code) as any;
return row ? this.mapRuleRow(row) : null;
}
public listRules(filter?: ListRulesFilter): RuleRecord[] {
const conditions: string[] = [];
const params: any[] = [];
if (filter?.scope) {
conditions.push("scope = ?");
params.push(filter.scope.trim());
}
if (filter?.status) {
conditions.push("status = ?");
params.push(filter.status);
}
let sql = "SELECT * FROM rules";
if (conditions.length > 0) {
sql += " WHERE " + conditions.join(" AND ");
}
sql += " ORDER BY code ASC";
const rows = this.db.query(sql).all(...params) as any[];
return rows.map((r) => this.mapRuleRow(r));
}
public countRules(filter?: ListRulesFilter): number {
const conditions: string[] = [];
const params: any[] = [];
if (filter?.scope) {
conditions.push("scope = ?");
params.push(filter.scope.trim());
}
if (filter?.status) {
conditions.push("status = ?");
params.push(filter.status);
}
let sql = "SELECT COUNT(*) as cnt FROM rules";
if (conditions.length > 0) {
sql += " WHERE " + conditions.join(" AND ");
}
const row = this.db.query(sql).get(...params) as { cnt: number } | null;
return row?.cnt ?? 0;
}
/**
* 获取去重后的所有索引(适用场景)列表及统计信息
* 每个索引按出现次序/最小编号分配 1-based 索引编号 (1, 2, 3...)
*/
public listScopes(status: "active" | "draft" | "archived" = "active"): ScopeSummary[] {
const rows = this.db
.query(`
SELECT scope, COUNT(*) as ruleCount, GROUP_CONCAT(code) as codeList
FROM rules
WHERE status = ?
GROUP BY scope
ORDER BY MIN(code) ASC
`)
.all(status) as any[];
return rows.map((row, idx) => {
const ruleCodes = String(row.codeList || "")
.split(",")
.map((c) => Number(c.trim()))
.filter((c) => !isNaN(c))
.sort((a, b) => a - b);
return {
index: idx + 1,
scope: row.scope,
ruleCount: Number(row.ruleCount),
ruleCodes
};
});
}
/**
* 根据 1-based 索引号或索引全名,获取该索引下的所有有效规约明细
*/
public getScopeDetail(indexOrName: number | string): ScopeDetail | null {
const scopes = this.listScopes("active");
let targetScope: ScopeSummary | undefined;
const trimmed = String(indexOrName).trim();
if (/^\d+$/.test(trimmed)) {
const idx = Number(trimmed);
targetScope = scopes.find((s) => s.index === idx);
} else {
targetScope = scopes.find(
(s) => s.scope.toLowerCase() === trimmed.toLowerCase()
);
}
if (!targetScope) {
return null;
}
const rules = this.listRules({ scope: targetScope.scope, status: "active" });
const detailedRules = rules.map((r) => {
const parsed = parseRuleBody(r.body);
return {
...r,
parsed
};
});
return {
index: targetScope.index,
scope: targetScope.scope,
ruleCount: targetScope.ruleCount,
rules: detailedRules
};
}
public updateRule(id: string, updates: UpdateRuleInput): RuleRecord {
const existing = this.getRuleById(id);
if (!existing) {
throw new Error(`未找到 ID 为 "${id}" 的规则`);
}
if (updates.body !== undefined) {
parseRuleBody(updates.body);
}
const now = Date.now();
const newScope = updates.scope !== undefined ? updates.scope.trim() : existing.scope;
const newBody = updates.body !== undefined ? updates.body.trim() : existing.body;
const newStatus = updates.status !== undefined ? updates.status : existing.status;
const newVersion = existing.version + 1;
this.db.run(
`
UPDATE rules
SET scope = ?, body = ?, status = ?, version = ?, updated_at = ?
WHERE id = ?
`,
[newScope, newBody, newStatus, newVersion, now, id]
);
return this.getRuleById(id)!;
}
public deleteRule(id: string): boolean {
const result = this.db.run("DELETE FROM rules WHERE id = ?", [id]);
return result.changes > 0;
}
// ===================== 风格偏好管理 (Preferences) =====================
public getDefaultPreference(): PreferenceRecord {
const row = this.db
.query("SELECT * FROM preferences WHERE is_default = 1 LIMIT 1")
.get() as any;
if (!row) {
const fallback = this.db
.query("SELECT * FROM preferences ORDER BY updated_at DESC LIMIT 1")
.get() as any;
if (!fallback) {
throw new Error("数据库未初始化默认偏好配置");
}
return this.mapPreferenceRow(fallback);
}
return this.mapPreferenceRow(row);
}
public getPreferenceById(id: string): PreferenceRecord | null {
const row = this.db.query("SELECT * FROM preferences WHERE id = ?").get(id) as any;
return row ? this.mapPreferenceRow(row) : null;
}
public updatePreference(
id: string,
updates: Partial<Omit<PreferenceRecord, "id" | "updatedAt">>
): PreferenceRecord {
const existing = this.getPreferenceById(id);
if (!existing) {
throw new Error(`未找到 ID 为 "${id}" 的偏好配置`);
}
if (updates.rulesReject !== undefined) validatePreferenceText(updates.rulesReject);
if (updates.rulesReview !== undefined) validatePreferenceText(updates.rulesReview);
if (updates.rulesPassNote !== undefined) validatePreferenceText(updates.rulesPassNote);
if (updates.rulesApprove !== undefined) validatePreferenceText(updates.rulesApprove);
const now = Date.now();
const name = updates.name ?? existing.name;
const isDefault = updates.isDefault !== undefined ? (updates.isDefault ? 1 : 0) : existing.isDefault ? 1 : 0;
const rulesReject = updates.rulesReject ?? existing.rulesReject;
const rulesReview = updates.rulesReview ?? existing.rulesReview;
const rulesPassNote = updates.rulesPassNote ?? existing.rulesPassNote;
const rulesApprove = updates.rulesApprove ?? existing.rulesApprove;
this.db.run(
`
UPDATE preferences
SET name = ?, is_default = ?, rules_reject = ?, rules_review = ?, rules_pass_note = ?, rules_approve = ?, updated_at = ?
WHERE id = ?
`,
[name, isDefault, rulesReject, rulesReview, rulesPassNote, rulesApprove, now, id]
);
return this.getPreferenceById(id)!;
}
// ===================== 审批运行与要点清单 (Runs & Findings) =====================
public createOrResetApprovalRun(input: CreateApprovalRunInput): ApprovalRunRecord {
const existing = this.getLatestRunBySn(input.documentSn);
const now = Date.now();
if (existing) {
// 清理旧要点,重置运行记录
this.db.run("DELETE FROM approval_findings WHERE run_id = ?", [existing.id]);
this.db.run(
`
UPDATE approval_runs
SET flow_id = ?, corp_id = ?, decision = ?, decision_summary = ?, matched_rules_count = ?, failed_rules_count = ?, document_snapshot = ?, updated_at = ?
WHERE id = ?
`,
[
(input.flowId !== undefined ? input.flowId : existing.flowId) ?? null,
(input.corpId !== undefined ? input.corpId : existing.corpId) ?? null,
input.decision ?? "PENDING",
(input.decisionSummary !== undefined ? input.decisionSummary : null) ?? null,
input.matchedRulesCount ?? 0,
input.failedRulesCount ?? 0,
(input.documentSnapshot !== undefined ? input.documentSnapshot : existing.documentSnapshot) ?? null,
now,
existing.id,
]
);
return this.getRunById(existing.id)!;
}
const id = crypto.randomUUID();
this.db.run(
`
INSERT INTO approval_runs (
id, flow_id, document_sn, corp_id, decision, decision_summary, matched_rules_count, failed_rules_count, document_snapshot, created_at, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`,
[
id,
input.flowId ?? null,
input.documentSn.trim(),
input.corpId ?? null,
input.decision ?? "PENDING",
input.decisionSummary ?? null,
input.matchedRulesCount ?? 0,
input.failedRulesCount ?? 0,
input.documentSnapshot ?? null,
now,
now,
]
);
return this.getRunById(id)!;
}
public getLatestRunBySn(documentSn: string): ApprovalRunRecord | null {
const row = this.db
.query("SELECT * FROM approval_runs WHERE document_sn = ? ORDER BY created_at DESC LIMIT 1")
.get(documentSn.trim()) as any;
return row ? this.mapRunRow(row) : null;
}
public getRunById(id: string): ApprovalRunRecord | null {
const row = this.db.query("SELECT * FROM approval_runs WHERE id = ?").get(id) as any;
return row ? this.mapRunRow(row) : null;
}
public updateApprovalRun(
id: string,
updates: Partial<Omit<ApprovalRunRecord, "id" | "documentSn" | "createdAt">>
): ApprovalRunRecord {
const existing = this.getRunById(id);
if (!existing) {
throw new Error(`未找到 ID 为 "${id}" 的审批运行记录`);
}
const now = Date.now();
const flowId = updates.flowId !== undefined ? updates.flowId : existing.flowId;
const corpId = updates.corpId !== undefined ? updates.corpId : existing.corpId;
const decision = updates.decision !== undefined ? updates.decision : existing.decision;
const decisionSummary = updates.decisionSummary !== undefined ? updates.decisionSummary : existing.decisionSummary;
const matchedRulesCount = updates.matchedRulesCount !== undefined ? updates.matchedRulesCount : existing.matchedRulesCount;
const failedRulesCount = updates.failedRulesCount !== undefined ? updates.failedRulesCount : existing.failedRulesCount;
const documentSnapshot = updates.documentSnapshot !== undefined ? updates.documentSnapshot : existing.documentSnapshot;
this.db.run(
`
UPDATE approval_runs
SET flow_id = ?, corp_id = ?, decision = ?, decision_summary = ?, matched_rules_count = ?, failed_rules_count = ?, document_snapshot = ?, updated_at = ?
WHERE id = ?
`,
[
flowId ?? null,
corpId ?? null,
decision ?? "PENDING",
decisionSummary ?? null,
matchedRulesCount,
failedRulesCount,
documentSnapshot ?? null,
now,
id,
]
);
return this.getRunById(id)!;
}
public injectFindings(runId: string, findings: CreateFindingInput[]): ApprovalFindingRecord[] {
const run = this.getRunById(runId);
if (!run) {
throw new Error(`审批运行记录不存在: ${runId}`);
}
const now = Date.now();
const insertStmt = this.db.prepare(`
INSERT INTO approval_findings (
id, run_id, rule_id, clause_text, strictness, check_status, evidence, reasoning, created_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
`);
for (const f of findings) {
const id = crypto.randomUUID();
insertStmt.run(
id,
runId,
f.ruleId ?? null,
f.clauseText.trim(),
f.strictness,
f.checkStatus ?? "PENDING",
f.evidence ?? null,
f.reasoning ?? null,
now
);
}
this.db.run(
"UPDATE approval_runs SET matched_rules_count = ?, updated_at = ? WHERE id = ?",
[findings.length, now, runId]
);
return this.getFindingsByRunId(runId);
}
public getFindingsByRunId(runId: string): ApprovalFindingRecord[] {
const rows = this.db
.query("SELECT * FROM approval_findings WHERE run_id = ? ORDER BY rowid ASC")
.all(runId) as any[];
return rows.map((r) => this.mapFindingRow(r));
}
public updateFinding(
findingId: string,
updates: {
checkStatus?: FindingCheckStatus;
evidence?: string | null;
reasoning?: string | null;
}
): ApprovalFindingRecord {
const row = this.db.query("SELECT * FROM approval_findings WHERE id = ?").get(findingId) as any;
if (!row) {
throw new Error(`未找到审核要点记录: ${findingId}`);
}
const checkStatus = updates.checkStatus ?? row.check_status;
const evidence = updates.evidence !== undefined ? updates.evidence : row.evidence;
const reasoning = updates.reasoning !== undefined ? updates.reasoning : row.reasoning;
this.db.run(
`
UPDATE approval_findings
SET check_status = ?, evidence = ?, reasoning = ?
WHERE id = ?
`,
[checkStatus, evidence, reasoning, findingId]
);
const updated = this.db.query("SELECT * FROM approval_findings WHERE id = ?").get(findingId) as any;
return this.mapFindingRow(updated);
}
public getAuditChecklist(documentSn: string): {
run: ApprovalRunRecord | null;
findings: ApprovalFindingRecord[];
} {
const run = this.getLatestRunBySn(documentSn);
if (!run) {
return { run: null, findings: [] };
}
const findings = this.getFindingsByRunId(run.id);
return { run, findings };
}
// ===================== 内部字段映射 =====================
private mapRuleRow(row: any): RuleRecord {
return {
id: row.id,
code: Number(row.code),
scope: row.scope,
body: row.body,
status: row.status,
version: Number(row.version),
createdAt: Number(row.created_at),
updatedAt: Number(row.updated_at)
};
}
private mapPreferenceRow(row: any): PreferenceRecord {
return {
id: row.id,
name: row.name,
isDefault: Boolean(row.is_default),
rulesReject: row.rules_reject,
rulesReview: row.rules_review,
rulesPassNote: row.rules_pass_note,
rulesApprove: row.rules_approve,
updatedAt: Number(row.updated_at)
};
}
private mapRunRow(row: any): ApprovalRunRecord {
return {
id: row.id,
flowId: row.flow_id,
documentSn: row.document_sn,
corpId: row.corp_id,
decision: row.decision as ApprovalDecision,
decisionSummary: row.decision_summary,
matchedRulesCount: Number(row.matched_rules_count || 0),
failedRulesCount: Number(row.failed_rules_count || 0),
documentSnapshot: row.document_snapshot,
createdAt: Number(row.created_at),
updatedAt: Number(row.updated_at),
};
}
private mapFindingRow(row: any): ApprovalFindingRecord {
let ruleCode: number | undefined;
if (row.rule_id) {
const rule = this.db.query("SELECT code FROM rules WHERE id = ?").get(row.rule_id) as any;
if (rule) ruleCode = Number(rule.code);
}
return {
id: row.id,
runId: row.run_id,
ruleId: row.rule_id,
ruleCode,
clauseText: row.clause_text,
strictness: row.strictness as StrictnessTier,
checkStatus: row.check_status as FindingCheckStatus,
evidence: row.evidence,
reasoning: row.reasoning,
createdAt: Number(row.created_at),
};
}
// ===================== AI PRO 审计监控日志 (Audit Logs) =====================
public logAiProAction(input: CreateAiProLogInput): AiProLogRecord {
const id = crypto.randomUUID();
const now = Date.now();
this.db.run(
`
INSERT INTO aipro_logs (id, action, document_sn, operator, args, status, decision, summary, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
`,
[
id,
input.action,
input.documentSn ?? null,
input.operator ?? null,
input.args ?? null,
input.status,
input.decision ?? null,
input.summary ?? null,
now,
]
);
return {
id,
action: input.action,
documentSn: input.documentSn,
operator: input.operator,
args: input.args,
status: input.status,
decision: input.decision,
summary: input.summary,
createdAt: now,
};
}
public listAiProLogs(documentSn?: string, limit = 50): AiProLogRecord[] {
let sql = "SELECT * FROM aipro_logs";
const params: any[] = [];
if (documentSn) {
sql += " WHERE document_sn = ?";
params.push(documentSn.trim());
}
sql += " ORDER BY created_at DESC LIMIT ?";
params.push(limit);
const rows = this.db.query(sql).all(...params) as any[];
return rows.map((r) => ({
id: r.id,
action: r.action,
documentSn: r.document_sn,
operator: r.operator,
args: r.args,
status: r.status as "SUCCESS" | "BLOCKED" | "ERROR",
decision: r.decision as ApprovalDecision | null,
summary: r.summary,
createdAt: Number(r.created_at),
}));
}
}
export interface CreateApprovalRunInput {
documentSn: string;
flowId?: string | null;
corpId?: string | null;
decision?: ApprovalDecision;
decisionSummary?: string | null;
matchedRulesCount?: number;
failedRulesCount?: number;
documentSnapshot?: string | null;
}
export interface CreateFindingInput {
ruleId?: string | null;
clauseText: string;
strictness: StrictnessTier;
checkStatus?: FindingCheckStatus;
evidence?: string | null;
reasoning?: string | null;
}
export interface CreateAiProLogInput {
action: string;
documentSn?: string | null;
operator?: string | null;
args?: string | null;
status: "SUCCESS" | "BLOCKED" | "ERROR";
decision?: ApprovalDecision | null;
summary?: string | null;
}
+331
View File
@@ -0,0 +1,331 @@
import { KyInstance } from "ky";
import { ApprovalRepository } from "./repository.js";
import { parseRuleBody } from "./parser.js";
import {
ApprovalDecision,
ApprovalFindingRecord,
ApprovalGatewayBlockedError,
ApprovalRunRecord,
FindingCheckStatus,
} from "./types.js";
import { getBillByCodeOrId, approveBill, rejectBill, commentBill } from "../bill/tools.js";
import type { FormattedBill } from "../bill/types.js";
export interface InjectPointsResult {
run: ApprovalRunRecord;
findings: ApprovalFindingRecord[];
bill: FormattedBill;
scope: string;
}
export interface DecideAuditOptions {
requestedAction?: "approve" | "reject" | "comment";
apply?: boolean;
comment?: string;
}
export interface DecideAuditResult {
run: ApprovalRunRecord;
decision: ApprovalDecision;
decisionSummary: string;
hardFailedCount: number;
elasticFailedCount: number;
suggestFailedCount: number;
specialFailedCount: number;
appliedAction?: "approve" | "reject" | "comment";
actionResult?: unknown;
}
export class ApprovalService {
private repo: ApprovalRepository;
constructor(repo?: ApprovalRepository) {
this.repo = repo ?? new ApprovalRepository();
}
/**
* 第一步:规则注入,提取单据明细级审核要点清单
*/
public async injectAuditPoints(
client: KyInstance,
corpId: string,
documentSn: string,
options: { scope?: string | number } = {}
): Promise<InjectPointsResult> {
// 1. 获取单据详情
const bills = await getBillByCodeOrId(client, corpId, documentSn);
if (bills.length === 0) {
throw new Error(`在当前企业下未找到单号或 ID 为 [${documentSn}] 的单据`);
}
const bill = bills[0];
const actualSn = bill.billCode || documentSn;
// 2. 匹配适用场景 (Scope)
let scopeDetail = options.scope !== undefined ? this.repo.getScopeDetail(options.scope) : null;
if (!scopeDetail) {
const allScopes = this.repo.listScopes();
if (allScopes.length === 0) {
throw new Error("规约库中暂无任何生效规则,请先使用 hose-use rule add <场景> <正文> 新增规则");
}
// 自动启发式场景匹配
const candidates = [bill.title, bill.stage, bill.billName].filter(Boolean) as string[];
let matchedSummary = allScopes.find((s) =>
candidates.some((c) => c.includes(s.scope) || s.scope.includes(c))
);
// 差旅特化匹配
if (!matchedSummary && candidates.some((c) => /差旅|出差|trip|hotel|住宿/i.test(c))) {
matchedSummary = allScopes.find((s) => /差旅|出差/i.test(s.scope));
}
// 默认回退至第一个场景
matchedSummary = matchedSummary ?? allScopes[0];
scopeDetail = this.repo.getScopeDetail(matchedSummary.index);
}
if (!scopeDetail || scopeDetail.rules.length === 0) {
throw new Error(`适用场景 [${options.scope ?? "自动匹配"}] 下暂无任何生效规则`);
}
// 3. 提取所有规则的 AST 条款要点
const clauseInputs: Array<{
ruleId: string;
ruleCode: number;
clauseText: string;
strictness: any;
}> = [];
for (const rule of scopeDetail.rules) {
const parsed = parseRuleBody(rule.body);
for (const clause of parsed.clauses) {
clauseInputs.push({
ruleId: rule.id,
ruleCode: rule.code,
clauseText: clause.action,
strictness: clause.strictness,
});
}
}
if (clauseInputs.length === 0) {
throw new Error(`场景 [${scopeDetail.scope}] 下的规则正文中未解析出任何合法判定要点 ([动作]{级别})`);
}
// 4. 为单据创建/重置审批运行记录
const run = this.repo.createOrResetApprovalRun({
documentSn: actualSn,
flowId: bill.billId,
corpId,
decision: "PENDING",
matchedRulesCount: clauseInputs.length,
failedRulesCount: 0,
documentSnapshot: JSON.stringify(bill),
});
// 5. 注入待核验要点清单 (Checklist)
const findings = this.repo.injectFindings(
run.id,
clauseInputs.map((c) => ({
ruleId: c.ruleId,
clauseText: c.clauseText,
strictness: c.strictness,
checkStatus: "PENDING",
}))
);
return {
run,
findings,
bill,
scope: scopeDetail.scope,
};
}
/**
* 查看单据当前审核清单状态
*/
public getAuditChecklist(documentSn: string) {
return this.repo.getAuditChecklist(documentSn);
}
/**
* 第二步:对注入的要点逐项进行事实核验判定
*/
public evaluateAuditPoints(
documentSn: string,
evaluations: Array<{
index?: number;
id?: string;
status: FindingCheckStatus;
evidence?: string;
reasoning?: string;
}>
): ApprovalFindingRecord[] {
const { run, findings } = this.repo.getAuditChecklist(documentSn);
if (!run || findings.length === 0) {
throw new ApprovalGatewayBlockedError(
`[审批链路阻断] 单据 [${documentSn}] 尚未注入任何审核要点清单(要点列表为空)。\n` +
`在没有注入审核要点的情况下,无法进行事实核验!\n` +
`请先执行: hose-use approval audit points ${documentSn} 注入审核要点清单。`
);
}
for (const item of evaluations) {
let target: ApprovalFindingRecord | undefined;
if (item.id) {
target = findings.find((f) => f.id === item.id);
} else if (item.index !== undefined) {
target = findings[item.index - 1];
}
if (!target) {
throw new Error(`未找到要点: ${item.id ?? `#${item.index}`}`);
}
this.repo.updateFinding(target.id, {
checkStatus: item.status,
evidence: item.evidence,
reasoning: item.reasoning,
});
}
return this.repo.getFindingsByRunId(run.id);
}
/**
* 第三步:确定性网关裁决与下游流转
*/
public async decideAudit(
client: KyInstance,
corpId: string,
documentSn: string,
options: DecideAuditOptions = {}
): Promise<DecideAuditResult> {
const { run, findings } = this.repo.getAuditChecklist(documentSn);
// ── 核心门禁 1:如果审核要点列表为空,审批链路物理不通! ────────────────────
if (!run || findings.length === 0) {
throw new ApprovalGatewayBlockedError(
`[审批链路阻断] 单据 [${documentSn}] 尚未注入任何明细级审核要点(要点列表为空)!\n` +
`网关卡点生效:审核要点未注入前,审批链路物理切断,绝对禁止进入审批决策!\n` +
`请先执行: hose-use approval audit points ${documentSn} 注入审核要点。`
);
}
// ── 核心门禁 2:检查是否有未完成事实核验的 PENDING 要点 ──────────────────────
const pendingFindings = findings.filter((f) => f.checkStatus === "PENDING");
if (pendingFindings.length > 0) {
throw new ApprovalGatewayBlockedError(
`[审批链路阻断] 单据 [${documentSn}] 尚有 ${pendingFindings.length} 处审核要点处于 PENDING 待核验状态!\n` +
`网关卡点生效:禁止在核验未全部闭环前提前决断。\n` +
`待核验项: ${pendingFindings.map((f, i) => `#${i + 1} [${f.strictness}] ${f.clauseText}`).join(";")}`
);
}
// ── 核心门禁 3:梯度级别与硬性刚性防线 ───────────────────────────────────────
const failedFindings = findings.filter((f) => f.checkStatus === "FAIL");
const hardFailed = failedFindings.filter((f) => f.strictness === "硬性");
const specialFailed = failedFindings.filter((f) => f.strictness === "特殊");
const elasticFailed = failedFindings.filter((f) => f.strictness === "弹性");
const suggestFailed = failedFindings.filter((f) => f.strictness === "建议");
// 硬性条款违规拦截:物理切断 approve 通道
if (hardFailed.length > 0 && options.requestedAction === "approve") {
const violatedNames = hardFailed.map((f) => `【${f.clauseText}】`).join("、");
throw new ApprovalGatewayBlockedError(
`[网关强力阻断] 单据 [${documentSn}] 触犯刚性底线【硬性】违规条款: ${violatedNames}!\n` +
`网关物理切断同意分支,绝对禁止放行通过!当前只允许执行驳回 (reject) 或建议复核。`
);
}
// 计算网关裁决决策
let decision: ApprovalDecision;
if (hardFailed.length > 0) {
decision = "REJECT";
} else if (specialFailed.length > 0) {
decision = "REVIEW";
} else if (elasticFailed.length > 0) {
decision = elasticFailed.length >= 3 ? "REVIEW" : "PASS_WITH_NOTE";
} else if (suggestFailed.length > 0) {
decision = "PASS_WITH_NOTE";
} else {
decision = "APPROVE";
}
// 组装格式化合规意见报告
const summaryLines: string[] = [];
summaryLines.push(`【合思 AI 确定性网关审查报告】`);
summaryLines.push(`单号: ${documentSn} | 审核要点总数: ${findings.length} 项`);
summaryLines.push(``);
summaryLines.push(`[逐项核验事实]`);
findings.forEach((f, idx) => {
const icon = f.checkStatus === "PASS" ? "✅" : f.checkStatus === "FAIL" ? "❌" : "➖";
const reason = f.evidence || f.reasoning ? ` (${[f.evidence, f.reasoning].filter(Boolean).join(" - ")})` : "";
summaryLines.push(` ${icon} #${idx + 1} [${f.strictness}] ${f.clauseText}${reason}`);
});
summaryLines.push(``);
if (decision === "REJECT") {
summaryLines.push(`[网关结论] ❌ 触犯硬性刚性条款,决策锁定为【驳回】`);
} else if (decision === "REVIEW") {
summaryLines.push(`[网关结论] ⚠️ 触发特殊或弹性超标条款,决策锁定为【建议人工复核】`);
} else if (decision === "PASS_WITH_NOTE") {
summaryLines.push(`[网关结论] 💡 满足核心要求,包含弹性/建议提示,决策锁定为【备注通过】`);
} else {
summaryLines.push(`[网关结论] ✅ 所有规则判定全部通过,决策锁定为【同意通过】`);
}
if (options.comment) {
summaryLines.push(`[审批附加说明] ${options.comment}`);
}
const decisionSummary = summaryLines.join("\n");
// 4. 更新数据库中的运行记录状态
this.repo.updateApprovalRun(run.id, {
decision,
decisionSummary,
failedRulesCount: failedFindings.length,
});
let appliedAction = options.requestedAction;
let actionResult: unknown = undefined;
// 5. 如果开启了 --apply,由网关在内部安全受控地调用下游接口
if (options.apply) {
if (!appliedAction) {
appliedAction = decision === "REJECT" ? "reject" : decision === "APPROVE" || decision === "PASS_WITH_NOTE" ? "approve" : "comment";
}
if (appliedAction === "reject") {
actionResult = await rejectBill(client, corpId, documentSn, {
comment: decisionSummary,
});
} else if (appliedAction === "approve") {
actionResult = await approveBill(client, corpId, documentSn, {
comment: decisionSummary,
});
} else {
actionResult = await commentBill(client, corpId, documentSn, {
comment: decisionSummary,
});
}
}
const updatedRun = this.repo.getRunById(run.id)!;
return {
run: updatedRun,
decision,
decisionSummary,
hardFailedCount: hardFailed.length,
elasticFailedCount: elasticFailed.length,
suggestFailedCount: suggestFailed.length,
specialFailedCount: specialFailed.length,
appliedAction,
actionResult,
};
}
}
+135
View File
@@ -0,0 +1,135 @@
export type StrictnessTier = "硬性" | "弹性" | "建议" | "特殊";
export const VALID_STRICTNESS_TIERS: readonly StrictnessTier[] = [
"硬性",
"弹性",
"建议",
"特殊"
] as const;
export function isValidStrictnessTier(value: string): value is StrictnessTier {
return (VALID_STRICTNESS_TIERS as readonly string[]).includes(value);
}
export interface RuleClause {
/** 抽取的动作句式文本,如 "一定需要上传发票" */
action: string;
/** 严格程度级别 */
strictness: StrictnessTier;
/** 原始标记子串,如 "[一定需要上传发票]{硬性}" */
raw: string;
/** 在正文中的起始字符索引 */
startIndex: number;
/** 在正文中的结束字符索引 */
endIndex: number;
}
export interface ParsedRule {
/** 原始正文 */
rawBody: string;
/** 解析出的所有判定要点 */
clauses: RuleClause[];
/** 剥离语法包裹后的纯文本,用于全文检索与语境理解 */
cleanText: string;
}
export interface ScopeSummary {
/** 1-based 索引编号 (1, 2, 3...),供 AI 和 CLI 快捷定位 */
index: number;
/** 适用场景名称/索引全名 */
scope: string;
/** 该索引下包含的有效规则总数 */
ruleCount: number;
/** 归属该索引的所有规则编号数组 (如 [1, 2, 4]) */
ruleCodes: number[];
}
export interface ScopeDetail {
index: number;
scope: string;
ruleCount: number;
rules: Array<RuleRecord & { parsed: ParsedRule }>;
}
export interface RuleRecord {
id: string;
code: number;
scope: string;
body: string;
status: "active" | "draft" | "archived";
version: number;
createdAt: number;
updatedAt: number;
}
export interface PreferenceRecord {
id: string;
name: string;
isDefault: boolean;
rulesReject: string;
rulesReview: string;
rulesPassNote: string;
rulesApprove: string;
updatedAt: number;
}
export type ApprovalDecision = "PENDING" | "APPROVE" | "REJECT" | "PASS_WITH_NOTE" | "REVIEW" | "ERROR";
export interface ApprovalRunRecord {
id: string;
flowId?: string | null;
documentSn: string;
corpId?: string | null;
decision: ApprovalDecision;
decisionSummary?: string | null;
matchedRulesCount: number;
failedRulesCount: number;
documentSnapshot?: string | null;
createdAt: number;
updatedAt: number;
}
export type FindingCheckStatus = "PENDING" | "PASS" | "FAIL" | "SKIP";
export interface ApprovalFindingRecord {
id: string;
runId: string;
ruleId?: string | null;
ruleCode?: number | null;
clauseText: string;
strictness: StrictnessTier;
checkStatus: FindingCheckStatus;
evidence?: string | null;
reasoning?: string | null;
createdAt: number;
}
export class ApprovalRuleValidationError extends Error {
public readonly code = "RULE_VALIDATION_ERROR";
constructor(message: string) {
super(message);
this.name = "ApprovalRuleValidationError";
}
}
export class ApprovalGatewayBlockedError extends Error {
public readonly code = "APPROVAL_GATEWAY_BLOCKED";
constructor(message: string) {
super(message);
this.name = "ApprovalGatewayBlockedError";
}
}
export interface AiProLogRecord {
id: string;
action: string;
documentSn?: string | null;
operator?: string | null;
args?: string | null;
status: "SUCCESS" | "BLOCKED" | "ERROR";
decision?: ApprovalDecision | null;
summary?: string | null;
createdAt: number;
}
+147 -1
View File
@@ -646,6 +646,138 @@ export function formatSingleBill(
};
}
export function formatFlowAsBill(
raw: Record<string, unknown>,
dictionary: Map<string, { label: string; type: string }>
): FormattedBill {
const flow = (raw.flowId && typeof raw.flowId === "object" ? raw.flowId : {}) as Record<string, unknown>;
const form = (flow.form && typeof flow.form === "object" ? flow.form : {}) as Record<string, unknown>;
const billCode = (typeof form.code === "string" && form.code.trim()) || (typeof flow.id === "string" ? flow.id : String(raw.id || ""));
const title = (typeof form.title === "string" && form.title.trim()) || (typeof flow.title === "string" ? flow.title : undefined);
const billName = title || (flow.formType === "requisition" ? "差旅申请单" : "审批单据");
const stage = typeof flow.formType === "string" ? flow.formType : "flow";
const state = raw.nodeName
? `${raw.state || flow.state || "APPROVING"} (${raw.nodeName})`
: (typeof raw.state === "string" ? raw.state : typeof flow.state === "string" ? flow.state : "APPROVING");
let amountStr: string | undefined;
for (const key of ["requisitionMoney", "amount", "expenseMoney", "payMoney"]) {
const val = form[key];
if (val && typeof val === "object" && (val as any).standard !== undefined) {
const money = val as any;
amountStr = `${money.standardSymbol || "¥"}${money.standard} ${money.standardStrCode || "CNY"}`.trim();
break;
}
}
let submitterId: string | undefined;
const submitter = form.submitterId as Record<string, unknown> | undefined;
if (submitter && typeof submitter === "object") {
const name = submitter.name || "";
const code = submitter.code ? ` (${submitter.code})` : "";
const dept = (submitter.defaultDepartment as Record<string, unknown>)?.name;
submitterId = `${name}${code}${dept ? ` - ${dept}` : ""}`.trim();
} else if (typeof form.submitterId === "string") {
submitterId = form.submitterId;
}
let submitDateStr: string | undefined;
if (typeof form.submitDate === "number" && form.submitDate > 1000000000000) {
submitDateStr = new Date(form.submitDate).toLocaleString("zh-CN");
}
const createTimeNum = typeof flow.createTime === "number" ? flow.createTime : typeof raw.createTime === "number" ? raw.createTime : 0;
const updateTimeNum = typeof flow.updateTime === "number" ? flow.updateTime : typeof raw.updateTime === "number" ? raw.updateTime : 0;
const createTimeStr = createTimeNum > 0 ? new Date(createTimeNum).toLocaleString("zh-CN") : "";
const updateTimeStr = updateTimeNum > 0 ? new Date(updateTimeNum).toLocaleString("zh-CN") : "";
const readableDetails: Record<string, any> = {};
if (raw.nodeName) readableDetails["当前节点"] = raw.nodeName;
if (raw.id) readableDetails["任务 ID"] = raw.id;
if (flow.id) readableDetails["流程 ID"] = flow.id;
if (flow.formType) readableDetails["表单类型"] = flow.formType;
const detailsArray = Array.isArray(form.details) ? form.details : [];
if (detailsArray.length > 0) {
readableDetails["费用明细条数"] = `${detailsArray.length} 笔`;
detailsArray.forEach((item, idx) => {
const feeForm = (item.feeTypeForm && typeof item.feeTypeForm === "object" ? item.feeTypeForm : {}) as Record<string, unknown>;
const feeTypeId = typeof item.feeTypeId === "string" ? item.feeTypeId.split(":").at(-1) || item.feeTypeId : "费用";
let rowMoney = "";
if (feeForm.amount && typeof feeForm.amount === "object") {
const m = feeForm.amount as any;
rowMoney = `${m.standardSymbol || "¥"}${m.standard} ${m.standardStrCode || "CNY"}`.trim();
}
let cityStr = "";
if (typeof feeForm.city === "string") {
try {
const parsedCity = JSON.parse(feeForm.city);
if (Array.isArray(parsedCity) && parsedCity[0]?.label) {
cityStr = parsedCity[0].label;
} else {
cityStr = feeForm.city;
}
} catch {
cityStr = feeForm.city;
}
}
let dateStr = "";
if (typeof feeForm.feeDate === "number" && feeForm.feeDate > 1000000000000) {
dateStr = new Date(feeForm.feeDate).toLocaleDateString("zh-CN");
}
const reason = feeForm.consumptionReasons || feeForm.reason || "";
const attachments = Array.isArray(feeForm.attachments) ? feeForm.attachments.length : 0;
const summaryParts = [
`[${feeTypeId}]`,
cityStr,
rowMoney,
dateStr,
reason ? `事由: ${reason}` : "",
`附件: ${attachments} 个`,
].filter(Boolean);
readableDetails[`明细 #${idx + 1}`] = summaryParts.join(" | ");
if (reason) readableDetails[`明细 #${idx + 1} 事由`] = reason;
if (cityStr) readableDetails[`明细 #${idx + 1} 城市`] = cityStr;
});
}
for (const [k, v] of Object.entries(form)) {
if (["code", "title", "details", "submitterId", "submitDate", "requisitionMoney", "amount", "expenseMoney", "logs", "flowPlanId"].includes(k)) continue;
if (v === null || v === undefined || v === "") continue;
const meta = dictionary.get(k);
const bareKey = k.replace(/^E_[^_]+_/, "").replace(/^E_/, "");
const label = meta ? meta.label : (COMMON_FIELD_LABELS[k] || COMMON_FIELD_LABELS[bareKey] || k);
if (typeof v === "object") {
readableDetails[label] = JSON.stringify(v);
} else {
readableDetails[label] = v;
}
}
return {
billId: String(flow.id || raw.id || ""),
billCode,
billName,
title,
stage,
state,
amount: amountStr,
submitterId,
submitDate: submitDateStr,
corporationId: String(flow.corporationId || raw.corporationId || ""),
ownerId: typeof flow.ownerId === "object" ? (flow.ownerId as any)?.name : typeof flow.ownerId === "string" ? flow.ownerId : undefined,
createTime: createTimeStr,
updateTime: updateTimeStr,
details: readableDetails,
};
}
// ── 业务操作:按单号或 ID 精确查询单据 ─────────────────────────────────────────
export async function getBillByCodeOrId(
@@ -685,7 +817,21 @@ export async function getBillByCodeOrId(
return false;
});
return matched.map((it) => formatSingleBill(it, dictionary));
if (matched.length > 0) {
return matched.map((it) => formatSingleBill(it, dictionary));
}
// 3. 回退到审批流程/待办接口检索(支持申请单 Requisition、借款单、自由流待办)
try {
const rawFlow = await getRawBillFlow(client, corpId, cleanQuery);
if (rawFlow) {
return [formatFlowAsBill(rawFlow, dictionary)];
}
} catch {
// 忽略流程回退错误
}
return [];
}
function flowPerson(value: unknown): { id?: string; name?: string; code?: string } | undefined {
+2 -2
View File
@@ -1,6 +1,6 @@
import { describe, expect, test } from "bun:test";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
import { Client } from "@modelcontextprotocol/client";
import { InMemoryTransport } from "@modelcontextprotocol/server";
import {
createServer,
resolveMcpMode,
+4 -8
View File
@@ -1,9 +1,5 @@
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
CallToolRequestSchema,
ListToolsRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
import { Server } from "@modelcontextprotocol/server";
import { StdioServerTransport } from "@modelcontextprotocol/server/stdio";
import { z } from "zod";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
@@ -192,7 +188,7 @@ export function createServer(options: { mode?: HoseMcpMode; enabled?: boolean }
const fineGrainedTools = [...authTools, ...platformTools, ...billTools];
// 注册工具列表
server.setRequestHandler(ListToolsRequestSchema, async () => {
server.setRequestHandler("tools/list", async () => {
if (!enabled) {
return { tools: [] };
}
@@ -234,7 +230,7 @@ export function createServer(options: { mode?: HoseMcpMode; enabled?: boolean }
});
// 处理工具调用
server.setRequestHandler(CallToolRequestSchema, async (request) => {
server.setRequestHandler("tools/call", async (request: any) => {
if (!enabled) {
return cliResult({
stdout: "",
+1 -1
View File
@@ -1 +1 @@
export const VERSION = "0.6.1";
export const VERSION = "0.7.0";