Compare commits

..
7 Commits
Author SHA1 Message Date
yunyingk 9a2d4529f5 Merge pull request #58 from yunyingk/release/v0.8.0
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
chore(release): bump version to v0.8.0
2026-09-08 15:53:54 +08:00
gitea 3937d3799b chore(release): bump version to v0.8.0 2026-09-08 15:53:41 +08:00
yunyingk bcf8ac0de6 Merge pull request #57 from yunyingk/refactor_db_cache_cleanup
refactor(core): 规范数据库表结构、版本迁移与多级缓存体系加固
2026-09-08 15:49:57 +08:00
gitea 3a15b064fe refactor(core): 规范数据库表结构、版本迁移与多级缓存体系加固
- 数据库表规范化与原子事务版本迁移机制 (_schema_migrations)
- 增加 SQLite 复合主键、PRAGMA busy_timeout 与索引覆盖
- 构建统一两级协同缓存 (L1 Memory LRU + L2 SQLite 持久化)
- withCache 增加 In-flight Promise 去重并发防击穿 (单飞机制)
- 收敛 dimension、role、bill 与 token-store 缓存逻辑
- 100% 保持现有 API 契约与零功能删除
2026-09-08 15:49:27 +08:00
gitea 00cbf039eb chore(release): bump version to v0.7.5
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
2026-09-08 14:04:03 +08:00
yunyingk a2eb04c4c1 Merge pull request #56 from yunyingk/codex/issue-55-auth-bill
fix(auth): guard temporary token refresh and translate bill flow
2026-09-08 12:11:35 +08:00
gitea 3f015d8e22 fix(auth): guard temporary token refresh and translate bill flow 2026-09-08 12:08:12 +08:00
36 changed files with 1508 additions and 298 deletions

No files matched your search

+2
View File
@@ -46,3 +46,5 @@ data/
# Local roadmaps & scratch notes
*.local.md
.agents/
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "hose-use",
"version": "0.7.4",
"version": "0.8.0",
"description": "合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号登录、企业租户切换、单据明细检索、工作流管理、内置 HTTP 服务与常驻守护进程。",
"author": {
"name": "yingqing"
+1 -1
View File
@@ -1,4 +1,4 @@
# hose-use (v0.7.4)
# hose-use (v0.8.0)
合思/易快报(ekuaibao)企业级 CLI 命令行工具与底层 SDK。
+1 -1
View File
@@ -2,7 +2,7 @@
"openapi": "3.1.0",
"info": {
"title": "hose-use API & MCP Tools Specification",
"version": "0.7.4",
"version": "0.8.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.7.4
version: 0.8.0
description: >-
Unified Enterprise SaaS API, CLI, and MCP Specification for Ekuaibao (合思/易快报), EASO, and Piper Workflows.
servers:
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "hose-use",
"version": "0.7.4",
"version": "0.8.0",
"module": "src/server.ts",
"type": "module",
"bin": {
+4 -4
View File
@@ -1,12 +1,12 @@
---
name: hose-use
description: "v0.7.4: 合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号 API 登录、租户切换、单据检索与审批动作、工作流跨域扫描、内置 HTTP 交互文档与常驻守护进程。"
description: "v0.8.0: 合思/易快报 (ekuaibao) 企业级 SaaS CLI 与底层 SDK:多账号 API 登录、租户切换、单据检索与审批动作、工作流跨域扫描、内置 HTTP 交互文档与常驻守护进程。"
metadata:
version: 0.7.4
short-description: 合思/易快报企业级 CLI 工具与底层 SDK (v0.7.4)
version: 0.8.0
short-description: 合思/易快报企业级 CLI 工具与底层 SDK (v0.8.0)
---
# hose-use (v0.7.4)
# hose-use (v0.8.0)
在具备 MCP 的 AI 智能体环境中,**优先使用 `hose_cli` 单工具网关**,传入 `command: string` 执行;在终端或自动化脚本中,直接调用全局 `hose` 或 `hose-use` 命令行。
本 Skill 是智能体的路由分发层:保持主文档简明,遇到复杂业务时深入查阅对应的专属参考文档(`references/*.md`)。
+6
View File
@@ -49,11 +49,17 @@ hose-use corps add-link "https://wx2.ekuaibao.com/web/thirdparty.html?accessToke
# 可选附加别名与覆盖参数
hose-use corps add-link "<url>" --name="客户企业别名" --overwrite
# 未提供服务端 expTime 时,可显式指定本地有效期
hose-use corps add-link "<url>" --ttl 3d
hose-use corps add-link "<url>" --expires 3 # 等价于 3 天;--days 3 也可以
```
- **全自动识别与身份探测**:
- 自动从 URL 提取服务节点 `baseUrl`、集群环境 `cluster`(如 `wx2`、`app`)、`accessToken` 与 `corpId`;
- 自动向 `$UNITY` JWT 与主站 Session 反查员工工号 (`staffId`)、员工姓名、绑定手机、企业全称与是否企业管理员,无需手动寻找工号;
- 动态自适应多集群环境换票,确保主站单据审批与 EASO 低代码工作流平台权限全绿连通。
- 非账号来源(link/browser/assist/curl/manual)不会触发账号换票;Token 失效时提示重新导入链接。
- 服务端返回的 expTime 优先;未返回时不再强制套用 2 小时,可使用 `--ttl` / `--expires` 指定有效期。
### 代客协助凭证导入
```bash
+4
View File
@@ -240,6 +240,8 @@ async function handleImport(parsed: CliParsedArgs, runtime: CliRuntime): Promise
let staffId = stringOption(parsed.options, ["staff", "staffId"]);
let name = stringOption(parsed.options, ["name"]);
const overwrite = booleanOption(parsed.options, ["overwrite", "force", "f"], false);
const ttl = stringOption(parsed.options, ["ttl"]);
const expires = stringOption(parsed.options, ["expires", "days"]);
if (!raw && !accessToken && process.stdin.isTTY) {
raw = await prompt("请粘贴抓包文本 / cURL 命令行 / 协助免密 URL (直接回车则手动逐项输入): ");
@@ -270,6 +272,8 @@ async function handleImport(parsed: CliParsedArgs, runtime: CliRuntime): Promise
name,
baseUrl,
overwrite,
ttl,
expires,
source: raw && (raw.startsWith("http://") || raw.startsWith("https://")) ? "link" : undefined,
});
+2 -1
View File
@@ -6,6 +6,7 @@ import {
searchAndFormatBills,
getBillByCodeOrId,
getBillFlow,
formatBillFlowOperator,
getBillRisk,
getBillReferences,
getBillRelations,
@@ -339,7 +340,7 @@ export async function handleBillCommand(
entry.time ? new Date(entry.time).toLocaleString("zh-CN") : "-",
entry.nodeName || "-",
entry.action || "-",
entry.operator?.name || (entry.automatic ? "系统" : "-"),
formatBillFlowOperator(entry.operator, entry.automatic, entry.operator?.id?.toLowerCase().includes("ebot")),
entry.durationMs !== undefined ? `${Math.round(entry.durationMs / 1000)} 秒` : "-",
entry.skipped ? "自动跳过" : entry.automatic ? "自动" : "",
entry.comment || "-",
+5 -1
View File
@@ -160,6 +160,8 @@ async function handleAddLink(parsed: CliParsedArgs, runtime: CliRuntime): Promis
let linkUrl = parsed.args[0] || stringOption(parsed.options, ["url", "link"]);
const name = stringOption(parsed.options, ["name"]);
const overwrite = booleanOption(parsed.options, ["overwrite", "force", "f"], false);
const ttl = stringOption(parsed.options, ["ttl"]);
const expires = stringOption(parsed.options, ["expires", "days"]);
if (!linkUrl && process.stdin.isTTY) {
linkUrl = await prompt("请输入第三方协助/免密登录链接 URL: ");
@@ -168,7 +170,7 @@ async function handleAddLink(parsed: CliParsedArgs, runtime: CliRuntime): Promis
if (!linkUrl) {
return {
stdout: "",
stderr: "错误:必须提供协助/免密链接 URL!用法: hose-use corps add-link <url> [--name <企业别名>] [--overwrite]\n",
stderr: "错误:必须提供协助/免密链接 URL!用法: hose-use corps add-link <url> [--name <企业别名>] [--ttl 3d|--expires 3] [--overwrite]\n",
exitCode: 1,
};
}
@@ -177,6 +179,8 @@ async function handleAddLink(parsed: CliParsedArgs, runtime: CliRuntime): Promis
const corp = await importFromLink(linkUrl, {
name,
overwrite,
ttl,
expires,
});
if (runtime.jsonMode) {
+13 -2
View File
@@ -1,6 +1,6 @@
# Core 层说明
Core 层负责基础设施:企业配置管理、认证 Token 获取与缓存、HTTP 客户端工厂、统一异常语义。
Core 层负责基础设施:企业配置管理、认证 Token 获取与缓存、统一数据库与版本迁移、多级协同缓存、HTTP 客户端工厂、统一异常语义。
## 代码结构
@@ -13,7 +13,16 @@ src/core/
│ ├── ekb.ts # 快报主站三 Header 认证
│ ├── easo.ts # EASO(unity.ekuaibao.com)四步认证
│ ├── piper.ts # Piper(piper.ekuaibao.com)三步认证
│ ├── token-store.ts # 动态 Token 缓存(~/.cache/ekb-mcp/tokens.json)
│ ├── token-store.ts # 动态 Token 缓存(兼容 ~/.config/hose-use/tokens.json 与历史路径)
│ └── types.ts
├── cache/ # 统一多级协同缓存
│ ├── memory.ts # L1 内存缓存(TTL、容量限制、按命名空间清理)
│ ├── sqlite.ts # L2 SQLite 持久化缓存(跨 CLI 进程复用)
│ ├── multi-level.ts # 多级联动门面与 withCache 透明包装器
│ └── types.ts
├── db/ # 统一 SQLite 数据库与结构化版本迁移
│ ├── connection.ts # SQLite 单例、WAL 模式、文件权限 0o600 保护
│ ├── migrations.ts # 结构化增量迁移运行器(_schema_migrations)
│ └── types.ts
├── config/ # 企业配置管理
│ ├── loader.ts
@@ -29,3 +38,5 @@ src/core/
- `domains/*/api.ts` 只通过 `core/http/factory.ts` 或 `core/auth/*` 获取客户端
- `domains/*` 层只抛 `EkbError` 子类
- `server.ts` 负责把 `EkbError` 映射为 MCP error
- 业务域如果需要缓存,统一使用 `core/cache/` 提供的多级缓存门面
- 业务域如果需要持久化数据,统一接入 `core/db/` 并注册版本迁移
+52
View File
@@ -0,0 +1,52 @@
import { describe, expect, it } from "bun:test";
import { canRefreshCorpAccessToken, resolveLinkExpiresAt } from "./login.js";
import { createEkbClient } from "./ekb.js";
import type { CorpConfig } from "../config/types.js";
function corp(overrides: Partial<CorpConfig> = {}): CorpConfig {
return {
id: "corp-1",
name: "测试企业",
source: "link",
credentials: { accessToken: "token", corpId: "corp-1", staffId: "staff-1" },
...overrides,
baseUrl: overrides.baseUrl ?? "https://app.ekuaibao.com",
};
}
describe("core/auth/ekb refresh policy", () => {
it("only allows account credentials with an explicit account binding to refresh", () => {
expect(canRefreshCorpAccessToken(corp())).toBe(false);
expect(canRefreshCorpAccessToken(corp({ source: "browser", accountId: "86-1" }))).toBe(false);
expect(canRefreshCorpAccessToken(corp({ source: "account" }))).toBe(false);
expect(canRefreshCorpAccessToken(corp({ source: "account", accountId: "86-1" }))).toBe(true);
expect(canRefreshCorpAccessToken(corp({ source: "account", accountId: "86-1", session: { isShortTermToken: true } }))).toBe(false);
});
it("fails expired temporary credentials without retrying or refreshing", async () => {
const originalFetch = globalThis.fetch;
let calls = 0;
globalThis.fetch = (async () => {
calls += 1;
return new Response("expired", { status: 401 });
}) as unknown as typeof fetch;
try {
const client = await createEkbClient(corp());
await expect(client.get("api/test")).rejects.toThrow("临时凭证已过期,请使用 hose-use corps add-link 重新导入");
expect(calls).toBe(1);
} finally {
globalThis.fetch = originalFetch;
}
});
});
describe("core/auth/login link expiry", () => {
it("parses explicit ttl and expires durations", () => {
const base = 1_700_000_000_000;
expect(resolveLinkExpiresAt({ ttl: "72h" }, base)).toBe(base + 72 * 60 * 60 * 1000);
expect(resolveLinkExpiresAt({ ttl: "3d" }, base)).toBe(base + 3 * 24 * 60 * 60 * 1000);
expect(resolveLinkExpiresAt({ expires: "3" }, base)).toBe(base + 3 * 24 * 60 * 60 * 1000);
expect(resolveLinkExpiresAt({}, base)).toBeUndefined();
});
});
+16 -6
View File
@@ -1,6 +1,7 @@
import { CorpConfig } from "../config/types.js";
import { AuthenticationError } from "../errors.js";
import { createAuthClient } from "../http/factory.js";
import { refreshSingleCorpAccessToken } from "./login.js";
import { canRefreshCorpAccessToken, refreshSingleCorpAccessToken } from "./login.js";
export function getEkbHeaders(corp: CorpConfig): Record<string, string> {
return {
@@ -11,20 +12,29 @@ export function getEkbHeaders(corp: CorpConfig): Record<string, string> {
}
export async function createEkbClient(corp: CorpConfig) {
const canRefresh = canRefreshCorpAccessToken(corp);
// 1. 预检:若 Token 即将过期 (提前 refreshTtl 秒),静默无感自动续杯
if (corp.auth?.expiresAt) {
if (canRefresh && corp.auth?.expiresAt) {
const ttlMs = (corp.auth.refreshTtl || 300) * 1000;
if (Date.now() >= corp.auth.expiresAt - ttlMs) {
await refreshSingleCorpAccessToken(corp);
}
}
// 2. 使用带 401 自动重试与换票的 AuthClient
// 2. 仅账号凭证启用 401 自动重试与换票;临时凭证直接给出可操作错误
return createAuthClient({
prefixUrl: corp.baseUrl || "https://app.ekuaibao.com",
getHeaders: () => getEkbHeaders(corp),
onUnauthorized: async () => {
await refreshSingleCorpAccessToken(corp);
},
retryUnauthorized: canRefresh,
...(canRefresh
? {
onUnauthorized: async () => {
await refreshSingleCorpAccessToken(corp);
},
}
: {
onAuthFailure: () => new AuthenticationError("临时凭证已过期,请使用 hose-use corps add-link 重新导入"),
}),
});
}
+38 -4
View File
@@ -231,6 +231,8 @@ export interface F12ImportParams {
source?: import("../config/types.js").CredentialSource;
enterprisesDir?: string;
overwrite?: boolean;
ttl?: string | number;
expires?: string | number;
}
export interface ImportFromLinkOptions {
@@ -238,6 +240,34 @@ export interface ImportFromLinkOptions {
baseUrl?: string;
enterprisesDir?: string;
overwrite?: boolean;
ttl?: string | number;
expires?: string | number;
}
export function canRefreshCorpAccessToken(corp: CorpConfig): boolean {
return corp.source === "account" && !corp.session?.isShortTermToken && Boolean(corp.accountId);
}
function parseDurationMs(value: string | number, defaultUnit: "hours" | "days"): number {
const raw = String(value).trim().toLowerCase();
const match = raw.match(/^(\d+(?:\.\d+)?)\s*(h|hr|hrs|hour|hours|d|day|days)?$/);
if (!match) throw new AuthenticationError(`无效的有效期参数: ${value}(示例:3d、72h)`);
const amount = Number(match[1]);
if (!Number.isFinite(amount) || amount <= 0) {
throw new AuthenticationError(`有效期必须是大于 0 的数字: ${value}`);
}
const unit = match[2];
const isDays = unit ? ["d", "day", "days"].includes(unit) : defaultUnit === "days";
return amount * (isDays ? 24 : 1) * 60 * 60 * 1000;
}
export function resolveLinkExpiresAt(
options: { ttl?: string | number; expires?: string | number },
baseTime = Date.now()
): number | undefined {
if (options.ttl !== undefined) return baseTime + parseDurationMs(options.ttl, "hours");
if (options.expires !== undefined) return baseTime + parseDurationMs(options.expires, "days");
return undefined;
}
/**
@@ -361,6 +391,7 @@ export async function importCredentials(
let isAdmin: boolean | undefined;
let sourceChannel: string | undefined;
let jwtExpMs: number | undefined;
const requestedExpiresAt = resolveLinkExpiresAt(params);
try {
const jwtHeaders: Record<string, string> = {
@@ -495,9 +526,8 @@ export async function importCredentials(
expiresAt = sessionData.expTime;
} else if (jwtExpMs && jwtExpMs > 0) {
expiresAt = jwtExpMs;
} else if ((sessionData?.isAssistPlatform || source === "link") && sessionData?.loginTime) {
// 协助/免密平台短期调试 Token 通常 2 小时有效
expiresAt = sessionData.loginTime + 2 * 3600 * 1000;
} else if (requestedExpiresAt) {
expiresAt = requestedExpiresAt;
}
const corpConfig: CorpConfig = {
@@ -566,6 +596,8 @@ export async function importFromLink(
enterprisesDir: options.enterprisesDir,
overwrite: options.overwrite,
source: "link",
ttl: options.ttl,
expires: options.expires,
});
}
@@ -679,7 +711,9 @@ export async function refreshSingleCorpAccessToken(
businessCenterUrl: string = DEFAULT_BUSINESS_CENTER_URL,
idpUrl: string = DEFAULT_IDP_URL
): Promise<boolean> {
const account = corp.accountId ? getAccount(corp.accountId) : getActiveAccount();
if (!canRefreshCorpAccessToken(corp)) return false;
const account = getAccount(corp.accountId!);
if (!account?.cloudAuthToken) return false;
try {
+72 -13
View File
@@ -1,31 +1,82 @@
import { readFileSync, writeFileSync, mkdirSync } from "fs";
import { join, dirname } from "path";
import { chmodSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "fs";
import { homedir } from "os";
import { dirname, join } from "path";
import { TokenStore, TokenStoreSchema } from "./types";
const TOKEN_CACHE_PATH = join(
export const PRIMARY_TOKEN_CACHE_PATH = join(
homedir(),
".config",
"hose-use",
"tokens.json"
);
export const LEGACY_TOKEN_CACHE_PATH = join(
homedir(),
".cache",
"ekb-mcp",
"tokens.json"
);
function ensureDir(path: string): void {
mkdirSync(dirname(path), { recursive: true });
function resolveTokenCachePath(): string {
if (existsSync(PRIMARY_TOKEN_CACHE_PATH)) {
return PRIMARY_TOKEN_CACHE_PATH;
}
if (existsSync(LEGACY_TOKEN_CACHE_PATH)) {
return LEGACY_TOKEN_CACHE_PATH;
}
return PRIMARY_TOKEN_CACHE_PATH;
}
export function loadTokenStore(): TokenStore {
try {
const content = readFileSync(TOKEN_CACHE_PATH, "utf-8");
return TokenStoreSchema.parse(JSON.parse(content));
} catch {
return {};
function ensureDir(path: string): void {
const dir = dirname(path);
if (!existsSync(dir)) {
mkdirSync(dir, { recursive: true, mode: 0o700 });
}
try {
chmodSync(dir, 0o700);
} catch {}
}
let memoryTokenCache: TokenStore | null = null;
let lastMtimeMs = 0;
export function loadTokenStore(): TokenStore {
const filePath = resolveTokenCachePath();
if (existsSync(filePath)) {
try {
const stats = statSync(filePath);
if (memoryTokenCache && stats.mtimeMs === lastMtimeMs) {
return memoryTokenCache;
}
const content = readFileSync(filePath, "utf-8");
const parsed = TokenStoreSchema.parse(JSON.parse(content));
memoryTokenCache = parsed;
lastMtimeMs = stats.mtimeMs;
return parsed;
} catch {
// 若已有内存缓存则保留,避免解析失败直接冲刷为 {}
return memoryTokenCache ?? {};
}
}
return memoryTokenCache ?? {};
}
export function saveTokenStore(store: TokenStore): void {
ensureDir(TOKEN_CACHE_PATH);
writeFileSync(TOKEN_CACHE_PATH, JSON.stringify(store, null, 2));
memoryTokenCache = store;
const targetPath = PRIMARY_TOKEN_CACHE_PATH;
ensureDir(targetPath);
// MAJ-03: 强制写入 0o600 保护敏感凭证
writeFileSync(targetPath, JSON.stringify(store, null, 2), {
encoding: "utf-8",
mode: 0o600,
});
try {
chmodSync(targetPath, 0o600);
lastMtimeMs = statSync(targetPath).mtimeMs;
} catch {}
}
export function getCorpTokens(corpId: string): TokenStore[string] | undefined {
@@ -44,3 +95,11 @@ export function clearCorpTokens(corpId: string): void {
delete store[corpId];
saveTokenStore(store);
}
/**
* 重置内存 Token 缓存(测试隔离用)
*/
export function resetTokenStoreMemory(): void {
memoryTokenCache = null;
lastMtimeMs = 0;
}
+162
View File
@@ -0,0 +1,162 @@
import { Database } from "bun:sqlite";
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { closeDatabase, getDatabase } from "../db/connection.js";
import { MemoryCache } from "./memory.js";
import { MultiLevelCache } from "./multi-level.js";
import { SqliteCache } from "./sqlite.js";
describe("Core Cache - 多级缓存架构与淘汰机制 (加固测试)", () => {
let db: Database;
beforeEach(() => {
db = getDatabase(":memory:");
});
afterEach(() => {
closeDatabase();
});
describe("L1: MemoryCache", () => {
test("基础读写、删除与命名空间隔离", () => {
const cache = new MemoryCache();
cache.set("100", { name: "用户A" }, { namespace: "users" });
cache.set("100", { title: "角色B" }, { namespace: "roles" });
// CRIT-02 验证:相同 key 在不同命名空间下完全隔离、互不覆写
expect(cache.get<{ name: string }>("100", "users")).toEqual({ name: "用户A" });
expect(cache.get<{ title: string }>("100", "roles")).toEqual({ title: "角色B" });
expect(cache.has("100", "users")).toBe(true);
expect(cache.has("100", "departments")).toBe(false);
// 按 namespace 清理
cache.clear("users");
expect(cache.get("100", "users")).toBeUndefined();
expect(cache.get<{ title: string }>("100", "roles")).toEqual({ title: "角色B" });
// 单条删除
cache.delete("100", "roles");
expect(cache.get("100", "roles")).toBeUndefined();
});
test("TTL 过期检查", async () => {
const cache = new MemoryCache();
cache.set("temp", "value", { ttlMs: 10 });
expect(cache.get<string>("temp")).toBe("value");
await new Promise((r) => setTimeout(r, 20));
expect(cache.get("temp")).toBeUndefined();
});
test("严格 LRU 访问热度调整与容量淘汰 (MAJ-08 & MAJ-09)", () => {
const cache = new MemoryCache(3);
cache.set("k1", "v1");
cache.set("k2", "v2");
cache.set("k3", "v3");
// 访问 k1,使 k1 成为最热的条目(移至队尾)
expect(cache.get<string>("k1")).toBe("v1");
// 此时最冷的是 k2。插入 k4 触发容量超限(容量 3)
cache.set("k4", "v4");
// 验证 k2 被淘汰,而最近被访问的 k1 依然存活
expect(cache.get("k2")).toBeUndefined();
expect(cache.get<string>("k1")).toBe("v1");
expect(cache.get<string>("k3")).toBe("v3");
expect(cache.get<string>("k4")).toBe("v4");
// 更新已有键不会增加容量,也不会误伤淘汰其他键
cache.set("k1", "v1_updated");
expect(cache.size()).toBe(3);
expect(cache.get<string>("k1")).toBe("v1_updated");
});
});
describe("L2: SqliteCache", () => {
test("复合主键 (namespace, key) 跨域存储与隔离 (CRIT-02)", () => {
const cache = new SqliteCache(db);
cache.set("id_1", { type: "dim" }, { namespace: "dimensions" });
cache.set("id_1", { type: "role" }, { namespace: "roles" });
const dim = cache.get<{ type: string }>("id_1", "dimensions");
const role = cache.get<{ type: string }>("id_1", "roles");
expect(dim?.type).toBe("dim");
expect(role?.type).toBe("role");
// 验证底层 SQLite 表结构行记录
const rows = db.query("SELECT namespace, key FROM cache_entries WHERE key = 'id_1'").all() as any[];
expect(rows.length).toBe(2);
// 按 namespace 清除
cache.clear("dimensions");
expect(cache.get("id_1", "dimensions")).toBeUndefined();
expect(cache.get("id_1", "roles")).toBeDefined();
});
test("TTL 过期与 pruneExpired 清理", async () => {
const cache = new SqliteCache(db);
cache.set("expire_soon", "data", { ttlMs: 15 });
expect(cache.get<string>("expire_soon")).toBe("data");
await new Promise((r) => setTimeout(r, 25));
expect(cache.get("expire_soon")).toBeUndefined();
cache.set("stale", "foo", { ttlMs: 5 });
await new Promise((r) => setTimeout(r, 15));
const pruned = cache.pruneExpired();
expect(pruned).toBeGreaterThanOrEqual(1);
});
});
describe("MultiLevelCache 两级协同与防击穿 (MAJ-01)", () => {
test("L1 miss 后从 L2 命中并自动回填至 L1", () => {
const l1 = new MemoryCache();
const l2 = new SqliteCache(db);
const multi = new MultiLevelCache({ l1, l2 });
multi.set("order:100", { amount: 888 }, { namespace: "orders" });
// 手动清空 L1 模拟内存冷启动
l1.clear();
expect(l1.get("order:100", "orders")).toBeUndefined();
// 从多级缓存读取:从 L2 命中,并回填至 L1
const val = multi.get<{ amount: number }>("order:100", "orders");
expect(val).toEqual({ amount: 888 });
// 验证 L1 已被自动回填
expect(l1.get<{ amount: number }>("order:100", "orders")).toEqual({ amount: 888 });
});
test("并发防击穿 (Thundering Herd Protection / In-flight Deduplication)", async () => {
const multi = new MultiLevelCache({ l2: new SqliteCache(db) });
let fetchCount = 0;
const slowFetcher = async () => {
fetchCount++;
await new Promise((r) => setTimeout(r, 20)); // 模拟慢网络
return { data: "fresh", fetchCount };
};
// 模拟 10 个并发请求在缓存冷启动时同时调用 withCache
const promises = Array.from({ length: 10 }).map(() =>
multi.withCache("concurrent_key", slowFetcher, {
namespace: "test_herd",
ttlMs: 5000,
})
);
const results = await Promise.all(promises);
// 验证:所有并发请求获取到相同的数据
expect(results.length).toBe(10);
for (const res of results) {
expect(res.fetchCount).toBe(1);
}
// 核心断言:底层 slowFetcher 严格只被调用了 1 次!彻底防御了缓存击穿
expect(fetchCount).toBe(1);
});
});
});
+35
View File
@@ -0,0 +1,35 @@
import { MultiLevelCache, type MultiLevelCacheOptions } from "./multi-level.js";
export * from "./types.js";
export * from "./memory.js";
export * from "./sqlite.js";
export * from "./multi-level.js";
let defaultCacheInstance: MultiLevelCache | null = null;
/**
* 获取全局默认多级缓存实例(单例)
*/
export function getGlobalCache(): MultiLevelCache {
if (!defaultCacheInstance) {
defaultCacheInstance = new MultiLevelCache();
}
return defaultCacheInstance;
}
/**
* 创建独立的多级缓存实例
*/
export function createMultiLevelCache(options?: MultiLevelCacheOptions): MultiLevelCache {
return new MultiLevelCache(options);
}
/**
* 重置全局缓存实例(测试清理用)
*/
export function resetGlobalCache(): void {
if (defaultCacheInstance) {
defaultCacheInstance.clear();
defaultCacheInstance = null;
}
}
+143
View File
@@ -0,0 +1,143 @@
import type { CacheEntry, CacheOptions, ICache } from "./types.js";
const DEFAULT_TTL_MS = 10 * 60 * 1000; // 10 分钟
const DEFAULT_MAX_ENTRIES = 2000;
export class MemoryCache implements ICache {
// Map 保持键的插入顺序,结合重新插入机制实现高效的 O(1) LRU 淘汰
private map = new Map<string, CacheEntry<any>>();
private maxEntries: number;
constructor(maxEntries = DEFAULT_MAX_ENTRIES) {
this.maxEntries = maxEntries;
}
/**
* CRIT-02: 构建命名空间隔离的复合内存键,彻底规避跨域碰撞
*/
private toCompositeKey(key: string, namespace?: string): string {
const ns = namespace || "default";
return `${ns}:${key}`;
}
public get<T>(key: string, namespace = "default"): T | undefined {
const compositeKey = this.toCompositeKey(key, namespace);
const entry = this.map.get(compositeKey);
if (!entry) return undefined;
const now = Date.now();
if (entry.expiresAt <= now) {
this.map.delete(compositeKey);
return undefined;
}
// MAJ-09: 真正 LRU 访问刷新 —— 命中后移至 Map 末尾
this.map.delete(compositeKey);
this.map.set(compositeKey, entry);
return entry.value as T;
}
public getEntry<T>(key: string, namespace = "default"): CacheEntry<T> | undefined {
const compositeKey = this.toCompositeKey(key, namespace);
const entry = this.map.get(compositeKey);
if (!entry) return undefined;
const now = Date.now();
if (entry.expiresAt <= now) {
this.map.delete(compositeKey);
return undefined;
}
// 命中后移至 Map 末尾保持热度
this.map.delete(compositeKey);
this.map.set(compositeKey, entry);
return entry as CacheEntry<T>;
}
public set<T>(key: string, value: T, options?: CacheOptions): void {
const namespace = options?.namespace ?? "default";
const compositeKey = this.toCompositeKey(key, namespace);
const now = Date.now();
const ttl = options?.ttlMs ?? DEFAULT_TTL_MS;
const entry: CacheEntry<T> = {
value,
expiresAt: now + ttl,
updatedAt: now,
namespace,
};
// MAJ-08: 更新已有键时,先删后插调至末尾,不应误触发 LRU 淘汰
if (this.map.has(compositeKey)) {
this.map.delete(compositeKey);
this.map.set(compositeKey, entry);
return;
}
// 若达到容量限制,执行 LRU 淘汰
if (this.map.size >= this.maxEntries) {
this.evict();
}
this.map.set(compositeKey, entry);
}
public setEntry<T>(key: string, entry: CacheEntry<T>): void {
const compositeKey = this.toCompositeKey(key, entry.namespace);
if (this.map.has(compositeKey)) {
this.map.delete(compositeKey);
} else if (this.map.size >= this.maxEntries) {
this.evict();
}
this.map.set(compositeKey, entry);
}
public delete(key: string, namespace = "default"): void {
const compositeKey = this.toCompositeKey(key, namespace);
this.map.delete(compositeKey);
}
public clear(namespace?: string): void {
if (!namespace) {
this.map.clear();
return;
}
const prefix = `${namespace}:`;
for (const k of this.map.keys()) {
if (k.startsWith(prefix)) {
this.map.delete(k);
}
}
}
public has(key: string, namespace = "default"): boolean {
return this.get(key, namespace) !== undefined;
}
public size(): number {
return this.map.size;
}
private evict(): void {
const now = Date.now();
// 1. 优先剔除已过期的死键
for (const [k, v] of this.map.entries()) {
if (v.expiresAt <= now) {
this.map.delete(k);
}
}
// 2. 若仍然超限,按真正的 LRU(头部为最久未访问的条目)淘汰最早的条目
while (this.map.size >= this.maxEntries) {
const oldestKey = this.map.keys().next().value;
if (oldestKey !== undefined) {
this.map.delete(oldestKey);
} else {
break;
}
}
}
}
+113
View File
@@ -0,0 +1,113 @@
import { MemoryCache } from "./memory.js";
import { SqliteCache } from "./sqlite.js";
import type { CacheOptions, ICache, WithCacheOptions } from "./types.js";
export interface MultiLevelCacheOptions {
l1?: MemoryCache;
l2?: SqliteCache | null;
}
export class MultiLevelCache implements ICache {
private l1: MemoryCache;
private l2: SqliteCache | null;
// MAJ-01: 防击穿 / 单飞并发请求去重表 (In-flight Promise Deduplication)
private inFlight = new Map<string, Promise<any>>();
constructor(options?: MultiLevelCacheOptions) {
this.l1 = options?.l1 ?? new MemoryCache();
this.l2 = options?.l2 !== undefined ? options.l2 : new SqliteCache();
}
public get<T>(key: string, namespace = "default"): T | undefined {
// 1. 优先从 L1 (Memory) 获取
const l1Value = this.l1.get<T>(key, namespace);
if (l1Value !== undefined) {
return l1Value;
}
// 2. L1 穿透,查询 L2 (SQLite 持久化)
if (this.l2) {
const l2Entry = this.l2.getEntry<T>(key, namespace);
if (l2Entry !== undefined) {
// 回填至 L1,保持相同的到期时间与命名空间
this.l1.setEntry(key, l2Entry);
return l2Entry.value;
}
}
return undefined;
}
public set<T>(key: string, value: T, options?: CacheOptions): void {
// 同时写入 L1 与 L2
this.l1.set(key, value, options);
if (this.l2) {
this.l2.set(key, value, options);
}
}
public delete(key: string, namespace = "default"): void {
this.l1.delete(key, namespace);
if (this.l2) {
this.l2.delete(key, namespace);
}
}
public clear(namespace?: string): void {
this.l1.clear(namespace);
if (this.l2) {
this.l2.clear(namespace);
}
}
public has(key: string, namespace = "default"): boolean {
return this.get(key, namespace) !== undefined;
}
/**
* MAJ-01: 业务透明包装器,自动多级缓存查验 + In-flight 请求合并防击穿
*/
public async withCache<T>(
key: string,
fetcher: () => Promise<T>,
options?: WithCacheOptions
): Promise<T> {
const namespace = options?.namespace ?? "default";
const lockKey = `${namespace}:${key}`;
if (!options?.forceRefresh) {
const cached = this.get<T>(key, namespace);
if (cached !== undefined) {
return cached;
}
}
// 防击穿:检查是否已有相同命名空间与键的并发请求在执行中
const ongoing = this.inFlight.get(lockKey);
if (ongoing) {
return ongoing as Promise<T>;
}
const promise = (async () => {
try {
const fresh = await fetcher();
this.set(key, fresh, options);
return fresh;
} finally {
this.inFlight.delete(lockKey);
}
})();
this.inFlight.set(lockKey, promise);
return promise;
}
/**
* 清理过期条目(MIN-11: L1 与 L2 同步清理)
*/
public pruneExpired(): void {
if (this.l2) {
this.l2.pruneExpired();
}
}
}
+128
View File
@@ -0,0 +1,128 @@
import type { Database } from "bun:sqlite";
import { getDatabase } from "../db/connection.js";
import type { CacheEntry, CacheOptions, ICache } from "./types.js";
const DEFAULT_TTL_MS = 10 * 60 * 1000; // 10 分钟
interface CacheRow {
namespace: string;
key: string;
value: string;
expires_at: number;
updated_at: number;
}
export class SqliteCache implements ICache {
private db: Database;
constructor(db?: Database) {
this.db = db ?? getDatabase();
}
public get<T>(key: string, namespace = "default"): T | undefined {
const entry = this.getEntry<T>(key, namespace);
return entry ? entry.value : undefined;
}
public getEntry<T>(key: string, namespace = "default"): CacheEntry<T> | undefined {
try {
const row = this.db
.query(
"SELECT namespace, key, value, expires_at, updated_at FROM cache_entries WHERE namespace = ? AND key = ?"
)
.get(namespace, key) as CacheRow | null;
if (!row) return undefined;
const now = Date.now();
if (row.expires_at <= now) {
this.delete(key, namespace);
return undefined;
}
const parsedValue = JSON.parse(row.value) as T;
return {
value: parsedValue,
expiresAt: row.expires_at,
updatedAt: row.updated_at,
namespace: row.namespace,
};
} catch {
// 容错处理损坏数据
this.delete(key, namespace);
return undefined;
}
}
public set<T>(key: string, value: T, options?: CacheOptions): void {
if (value === undefined) {
// MIN-05: undefined 语义等同于清除该键
this.delete(key, options?.namespace);
return;
}
const now = Date.now();
const ttl = options?.ttlMs ?? DEFAULT_TTL_MS;
const namespace = options?.namespace ?? "default";
const expiresAt = now + ttl;
try {
const serialized = JSON.stringify(value);
this.db.run(
`
INSERT INTO cache_entries (namespace, key, value, expires_at, updated_at)
VALUES (?, ?, ?, ?, ?)
ON CONFLICT(namespace, key) DO UPDATE SET
value = excluded.value,
expires_at = excluded.expires_at,
updated_at = excluded.updated_at
`,
[namespace, key, serialized, expiresAt, now]
);
} catch (err) {
console.error(`[cache] SqliteCache.set error for ${namespace}:${key}:`, err);
}
}
public delete(key: string, namespace = "default"): void {
try {
this.db.run(
"DELETE FROM cache_entries WHERE namespace = ? AND key = ?",
[namespace, key]
);
} catch {
// 容错
}
}
public clear(namespace?: string): void {
try {
if (namespace) {
this.db.run("DELETE FROM cache_entries WHERE namespace = ?", [namespace]);
} else {
this.db.run("DELETE FROM cache_entries");
}
} catch {
// 容错
}
}
public has(key: string, namespace = "default"): boolean {
return this.get(key, namespace) !== undefined;
}
/**
* 主动清理数据库中所有过期缓存记录
*/
public pruneExpired(): number {
try {
const result = this.db.run(
"DELETE FROM cache_entries WHERE expires_at <= ?",
[Date.now()]
);
return result.changes;
} catch {
return 0;
}
}
}
+32
View File
@@ -0,0 +1,32 @@
export interface CacheOptions {
/**
* 缓存有效时长(毫秒),默认 10 分钟 (600,000 ms)
*/
ttlMs?: number;
/**
* 命名空间,便于按业务模块隔离与批量失效(例如: 'dimensions', 'roles', 'bills')
*/
namespace?: string;
}
export interface CacheEntry<T> {
value: T;
expiresAt: number;
updatedAt: number;
namespace: string;
}
export interface ICache {
get<T>(key: string): Promise<T | undefined> | T | undefined;
set<T>(key: string, value: T, options?: CacheOptions): Promise<void> | void;
delete(key: string): Promise<void> | void;
clear(namespace?: string): Promise<void> | void;
has(key: string): Promise<boolean> | boolean;
}
export interface WithCacheOptions extends CacheOptions {
/**
* 是否强制穿透缓存刷新
*/
forceRefresh?: boolean;
}
+104
View File
@@ -0,0 +1,104 @@
import { Database } from "bun:sqlite";
import { chmodSync, existsSync, mkdirSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import { runMigrations } from "./migrations.js";
import type { DatabaseConnectionOptions } from "./types.js";
export const DEFAULT_DB_PATH = join(
homedir(),
".config",
"hose-use",
"approval.db"
);
export function resolveDatabasePath(): string {
const envPath = process.env.HOSE_APPROVAL_DB?.trim();
if (envPath) {
return envPath;
}
return DEFAULT_DB_PATH;
}
let activeDb: Database | null = null;
let currentDbPath: string | null = null;
/**
* 获取或创建 SQLite 数据库连接单例,自动执行版本迁移
*/
export function getDatabase(options?: DatabaseConnectionOptions | string): Database {
const customPath = typeof options === "string" ? options : options?.customPath;
const targetPath = customPath ?? resolveDatabasePath();
if (activeDb && currentDbPath === targetPath) {
return activeDb;
}
// 若存在旧的不同路径连接,先优雅关闭释放文件句柄 (MAJ-12)
if (activeDb && currentDbPath !== targetPath) {
closeDatabase();
}
// 内存数据库无需创建物理目录
if (targetPath !== ":memory:") {
const dir = dirname(targetPath);
if (!existsSync(dir)) {
mkdirSync(dir, { recursive: true, mode: 0o700 });
}
try {
chmodSync(dir, 0o700);
} catch {}
}
const db = new Database(targetPath);
if (targetPath !== ":memory:") {
// 保护敏感业务规则、缓存、会话与审计数据 (0o600)
try {
chmodSync(targetPath, 0o600);
} catch {
// 容错处理
}
}
// 启用 WAL 模式与并发优化
db.run("PRAGMA journal_mode = WAL;");
db.run("PRAGMA foreign_keys = ON;");
// 关键:避免 0ms 锁超时崩溃,允许并发等待 5000ms (MAJ-02)
db.run("PRAGMA busy_timeout = 5000;");
db.run("PRAGMA synchronous = NORMAL;");
try {
// 自动执行结构化原子迁移
runMigrations(db);
} catch (err) {
// CRIT-03: 若迁移失败,坚决不激活单例缓存,关闭句柄并向外抛出错误
try {
db.close();
} catch {}
activeDb = null;
currentDbPath = null;
throw err;
}
// 迁移彻底成功后,才正式激活单例
currentDbPath = targetPath;
activeDb = db;
return db;
}
/**
* 关闭并清理当前活跃数据库连接
*/
export function closeDatabase(): void {
if (activeDb) {
try {
activeDb.close();
} catch {
// 容错
}
activeDb = null;
currentDbPath = null;
}
}
+72
View File
@@ -0,0 +1,72 @@
import { Database } from "bun:sqlite";
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { closeDatabase, getDatabase } from "./connection.js";
import { runMigrations } from "./migrations.js";
describe("Core DB - 数据库连接与结构化迁移机制 (加固测试)", () => {
let db: Database;
beforeEach(() => {
db = getDatabase(":memory:");
});
afterEach(() => {
closeDatabase();
});
test("数据库初始化时自动应用所有版本迁移并记录到 _schema_migrations", () => {
const rows = db.query("SELECT version, name FROM _schema_migrations ORDER BY version ASC").all() as Array<{
version: number;
name: string;
}>;
expect(rows.length).toBeGreaterThanOrEqual(1);
expect(rows[0].version).toBe(1);
expect(rows[0].name).toBe("001_core_schema_and_approval_tables");
});
test("核心数据表与新增的多级缓存表结构完备且索引有效", () => {
// 检查表是否存在
const tables = db
.query("SELECT name FROM sqlite_master WHERE type = 'table'")
.all() as Array<{ name: string }>;
const tableNames = new Set(tables.map((t) => t.name));
expect(tableNames.has("rules")).toBe(true);
expect(tableNames.has("preferences")).toBe(true);
expect(tableNames.has("approval_runs")).toBe(true);
expect(tableNames.has("approval_findings")).toBe(true);
expect(tableNames.has("aipro_logs")).toBe(true);
expect(tableNames.has("cache_entries")).toBe(true);
// 检查加固索引:UPPER(short_id)、findings(rule_id)
const indices = db
.query("SELECT name FROM sqlite_master WHERE type = 'index'")
.all() as Array<{ name: string }>;
const indexNames = new Set(indices.map((i) => i.name));
expect(indexNames.has("idx_runs_corp_id")).toBe(true);
expect(indexNames.has("idx_runs_expires_at")).toBe(true);
expect(indexNames.has("idx_runs_flow_id")).toBe(true);
expect(indexNames.has("idx_runs_short_id_upper")).toBe(true);
expect(indexNames.has("idx_findings_rule_id")).toBe(true);
expect(indexNames.has("idx_cache_namespace")).toBe(true);
expect(indexNames.has("idx_cache_expires_at")).toBe(true);
});
test("cache_entries 具备复合主键 (namespace, key) 约束", () => {
db.run(
"INSERT INTO cache_entries (namespace, key, value, expires_at, updated_at) VALUES ('n1', 'k1', 'v1', 9999, 1000)"
);
// 相同 key 但不同 namespace 可以成功插入
db.run(
"INSERT INTO cache_entries (namespace, key, value, expires_at, updated_at) VALUES ('n2', 'k1', 'v2', 9999, 1000)"
);
const countRow = db.query("SELECT COUNT(*) AS c FROM cache_entries WHERE key = 'k1'").get() as { c: number };
expect(countRow.c).toBe(2);
});
test("再次执行 runMigrations 保证幂等且不抛错", () => {
expect(() => runMigrations(db)).not.toThrow();
});
});
+3
View File
@@ -0,0 +1,3 @@
export * from "./types.js";
export * from "./connection.js";
export * from "./migrations.js";
+211
View File
@@ -0,0 +1,211 @@
import type { Database } from "bun:sqlite";
import type { DatabaseMigration } from "./types.js";
function hasColumn(db: Database, tableName: string, columnName: string): boolean {
try {
const rows = db.query(`PRAGMA table_info(${tableName})`).all() as Array<{ name: string }>;
return rows.some((r) => r.name === columnName);
} catch {
return false;
}
}
export const migrations: DatabaseMigration[] = [
{
version: 1,
name: "001_core_schema_and_approval_tables",
up(db: Database): void {
// 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,
short_id TEXT,
expires_at INTEGER,
flow_id TEXT,
document_sn TEXT NOT NULL,
corp_id TEXT,
scope TEXT,
decision TEXT NOT NULL,
decision_summary TEXT,
matched_rules_count INTEGER NOT NULL DEFAULT 0,
failed_rules_count INTEGER NOT NULL DEFAULT 0,
document_snapshot TEXT,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
`);
// 增量兼容老库缺省列
if (!hasColumn(db, "approval_runs", "scope")) {
try { db.run("ALTER TABLE approval_runs ADD COLUMN scope TEXT;"); } catch {}
}
if (!hasColumn(db, "approval_runs", "short_id")) {
try { db.run("ALTER TABLE approval_runs ADD COLUMN short_id TEXT;"); } catch {}
}
if (!hasColumn(db, "approval_runs", "expires_at")) {
try { db.run("ALTER TABLE approval_runs ADD COLUMN expires_at INTEGER;"); } catch {}
}
db.run("CREATE INDEX IF NOT EXISTS idx_runs_document_sn ON approval_runs(document_sn);");
db.run("CREATE INDEX IF NOT EXISTS idx_runs_short_id ON approval_runs(short_id);");
// MAJ-06: 支持 UPPER(short_id) 大小写不敏感快速定位
db.run("CREATE INDEX IF NOT EXISTS idx_runs_short_id_upper ON approval_runs(UPPER(short_id));");
db.run("CREATE INDEX IF NOT EXISTS idx_runs_created_at ON approval_runs(created_at);");
db.run("CREATE INDEX IF NOT EXISTS idx_runs_corp_id ON approval_runs(corp_id);");
db.run("CREATE INDEX IF NOT EXISTS idx_runs_flow_id ON approval_runs(flow_id);");
db.run("CREATE INDEX IF NOT EXISTS idx_runs_expires_at ON approval_runs(expires_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);");
// MAJ-07: 补充外键索引,防止外键删除全表扫描
db.run("CREATE INDEX IF NOT EXISTS idx_findings_rule_id ON approval_findings(rule_id);");
// 5. 全流程操作与审计流水表
db.run(`
CREATE TABLE IF NOT EXISTS aipro_logs (
id TEXT PRIMARY KEY,
run_id TEXT,
action TEXT NOT NULL,
document_sn TEXT,
operator TEXT,
args TEXT,
status TEXT NOT NULL,
decision TEXT,
summary TEXT,
created_at INTEGER NOT NULL
);
`);
if (!hasColumn(db, "aipro_logs", "run_id")) {
try { db.run("ALTER TABLE aipro_logs ADD COLUMN run_id TEXT;"); } catch {}
}
db.run("CREATE INDEX IF NOT EXISTS idx_aipro_logs_document_sn ON aipro_logs(document_sn);");
db.run("CREATE INDEX IF NOT EXISTS idx_aipro_logs_run_id ON aipro_logs(run_id);");
db.run("CREATE INDEX IF NOT EXISTS idx_aipro_logs_created_at ON aipro_logs(created_at);");
// 6. 多级缓存持久化表 (L2 Persistent Cache)
// CRIT-02: 采用复合主键 (namespace, key),彻底杜绝跨命名空间键碰撞
db.run(`
CREATE TABLE IF NOT EXISTS cache_entries (
namespace TEXT NOT NULL,
key TEXT NOT NULL,
value TEXT NOT NULL,
expires_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
PRIMARY KEY (namespace, key)
);
`);
db.run("CREATE INDEX IF NOT EXISTS idx_cache_namespace ON cache_entries(namespace);");
db.run("CREATE INDEX IF NOT EXISTS idx_cache_expires_at ON cache_entries(expires_at);");
// 种子数据:初始化默认偏好(CRIT-05: 使用 INSERT OR IGNORE 保证多进程启动绝对幂等)
seedDefaultPreference(db);
},
},
];
function seedDefaultPreference(db: Database): void {
const now = Date.now();
// CRIT-05: 使用 INSERT OR IGNORE 消除多进程并发启动 UNIQUE 冲突
db.run(
`
INSERT OR IGNORE INTO preferences (
id, name, is_default, rules_reject, rules_review, rules_pass_note, rules_approve, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
`,
[
"default",
"标准财务审批偏好",
1,
"确认触犯任何 @{硬性} 条款(刚性底线,直接阻断)",
"触发任何 @{特殊} 条款;未满足 @{弹性} 条款且单据金额 > 500 元;未满足 @{弹性} 累计达 3 处以上;单据未命中任何已有规则",
"未满足 @{弹性} 条款但单据金额 <= 500 元(企业尺度豁免放行);未满足 @{建议} 条款(倡导性要求,附温馨提示)",
"所有条款全部满足,秒级免审全自动通过",
now,
]
);
}
/**
* 执行迁移:自动检测并按序原子执行未应用的 migration (CRIT-04)
*/
export function runMigrations(db: Database): void {
// 创建迁移历史版本表
db.run(`
CREATE TABLE IF NOT EXISTS _schema_migrations (
version INTEGER PRIMARY KEY,
name TEXT NOT NULL,
applied_at INTEGER NOT NULL
);
`);
const appliedRows = db
.query("SELECT version FROM _schema_migrations ORDER BY version ASC")
.all() as Array<{ version: number }>;
const appliedVersions = new Set(appliedRows.map((r) => r.version));
// 按版本号升序排列依次执行
const sortedMigrations = [...migrations].sort((a, b) => a.version - b.version);
for (const migration of sortedMigrations) {
if (!appliedVersions.has(migration.version)) {
// CRIT-04: 使用 BEGIN IMMEDIATE 事务原子包裹
db.run("BEGIN IMMEDIATE;");
try {
migration.up(db);
db.run(
"INSERT INTO _schema_migrations (version, name, applied_at) VALUES (?, ?, ?)",
[migration.version, migration.name, Date.now()]
);
db.run("COMMIT;");
} catch (err) {
try {
db.run("ROLLBACK;");
} catch {}
throw err;
}
}
}
}
+12
View File
@@ -0,0 +1,12 @@
import type { Database } from "bun:sqlite";
export interface DatabaseMigration {
version: number;
name: string;
up: (db: Database) => void;
}
export interface DatabaseConnectionOptions {
customPath?: string;
readOnly?: boolean;
}
+6 -1
View File
@@ -9,6 +9,8 @@ export interface CreateAuthClientOptions {
prefixUrl: string;
getHeaders: () => Promise<Record<string, string>> | Record<string, string>;
onUnauthorized?: () => Promise<void> | void;
onAuthFailure?: (response: Response) => Error;
retryUnauthorized?: boolean;
}
export function createClient(options: CreateClientOptions): KyInstance {
@@ -22,7 +24,7 @@ export function createAuthClient(options: CreateAuthClientOptions): KyInstance {
return ky.create({
prefix: options.prefixUrl,
retry: {
limit: 1,
limit: options.retryUnauthorized === false ? 0 : 1,
methods: ["get", "post", "put", "delete", "patch"],
statusCodes: [401],
},
@@ -59,6 +61,9 @@ export function createAuthClient(options: CreateAuthClientOptions): KyInstance {
}
return ky(request);
}
if (isAuthError && options.onAuthFailure) {
throw options.onAuthFailure(response);
}
return response;
},
],
+16 -181
View File
@@ -1,200 +1,35 @@
import { Database } from "bun:sqlite";
import { chmodSync, existsSync, mkdirSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import type { Database } from "bun:sqlite";
import {
DEFAULT_DB_PATH,
closeDatabase,
getDatabase,
resolveDatabasePath,
runMigrations,
} from "../../core/db/index.js";
export const DEFAULT_APPROVAL_DB_PATH = join(
homedir(),
".config",
"hose-use",
"approval.db"
);
export const DEFAULT_APPROVAL_DB_PATH = DEFAULT_DB_PATH;
export function resolveApprovalDbPath(): string {
const envPath = process.env.HOSE_APPROVAL_DB?.trim();
if (envPath) {
return envPath;
}
return DEFAULT_APPROVAL_DB_PATH;
return resolveDatabasePath();
}
let activeDb: Database | null = null;
let currentDbPath: string | null = null;
/**
* 获取或创建 SQLite 数据库连接单例
* 获取或创建 SQLite 数据库连接单例(兼容原接口,底层使用 core/db)
*/
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);
if (targetPath !== ":memory:") {
// 规则、单据快照、审核证据和审计日志都可能包含敏感信息。
// SQLite 默认文件权限受 umask 影响,不能依赖默认值保护凭证与业务数据。
chmodSync(targetPath, 0o600);
}
currentDbPath = targetPath;
activeDb = db;
initDatabaseSchema(db);
return db;
return getDatabase(customPath);
}
/**
* 关闭并清理当前数据库连接(用于测试重置或进程退出)
* 关闭并清理当前数据库连接
*/
export function closeApprovalDatabase(): void {
if (activeDb) {
activeDb.close();
activeDb = null;
currentDbPath = null;
}
closeDatabase();
}
/**
* 初始化表结构与默认数据
* 初始化表结构与默认数据(兼容原接口,委托给 runMigrations)
*/
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,
short_id TEXT,
expires_at INTEGER,
flow_id TEXT,
document_sn TEXT NOT NULL,
corp_id TEXT,
scope TEXT,
decision TEXT NOT NULL,
decision_summary TEXT,
matched_rules_count INTEGER NOT NULL DEFAULT 0,
failed_rules_count INTEGER NOT NULL DEFAULT 0,
document_snapshot TEXT,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
`);
try {
db.run("ALTER TABLE approval_runs ADD COLUMN scope TEXT;");
} catch {}
try {
db.run("ALTER TABLE approval_runs ADD COLUMN short_id TEXT;");
} catch {}
try {
db.run("ALTER TABLE approval_runs ADD COLUMN expires_at INTEGER;");
} catch {}
db.run("CREATE INDEX IF NOT EXISTS idx_runs_document_sn ON approval_runs(document_sn);");
db.run("CREATE INDEX IF NOT EXISTS idx_runs_short_id ON approval_runs(short_id);");
db.run("CREATE INDEX IF NOT EXISTS idx_runs_created_at ON approval_runs(created_at);");
// 4. 审批要点事实记录表
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,
run_id TEXT,
action TEXT NOT NULL,
document_sn TEXT,
operator TEXT,
args TEXT,
status TEXT NOT NULL,
decision TEXT,
summary TEXT,
created_at INTEGER NOT NULL
);
`);
try {
db.run("ALTER TABLE aipro_logs ADD COLUMN run_id TEXT;");
} catch {}
db.run("CREATE INDEX IF NOT EXISTS idx_aipro_logs_document_sn ON aipro_logs(document_sn);");
db.run("CREATE INDEX IF NOT EXISTS idx_aipro_logs_run_id ON aipro_logs(run_id);");
db.run("CREATE INDEX IF NOT EXISTS idx_aipro_logs_created_at ON aipro_logs(created_at);");
// 种子数据:初始化默认偏好
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
]
);
}
runMigrations(db);
}
+33
View File
@@ -210,6 +210,39 @@ describe("Bill Domain", () => {
expect(result?.history[1]?.skipped).toBe(true);
});
it("translates flow actions, states, Ebot operators and print reminders", async () => {
const client = {
post: async (path: string) => {
if (path.includes("backlogs/search")) {
return new Response(JSON.stringify({ items: [{ id: "backlog-i18n", flowId: { id: "flow-i18n", form: { code: "B26000001" } } }] }));
}
return new Response(JSON.stringify({ value: {
id: "backlog-i18n",
state: "APPROVING",
flowId: {
id: "flow-i18n",
state: "APPROVING",
form: { code: "B26000001" },
logs: [
{ action: "freeflow.submit", state: "SUBMITTED", operatorId: "staff-1", attributes: { nodeName: "提交" } },
{ action: "freeflow.autoAgree", state: "APPROVED", operatorId: "ebot", attributes: { isEbotNode: true } },
{ action: "freeflow.print", state: "COMPLETED", attributes: { isAuto: true } },
],
plan: { nodes: [{ id: "node-next", name: "财务审批", type: "APPROVAL" }] },
},
} }));
},
} as any;
const result = await getBillFlow(client, "corp-i18n", "B26000001");
expect(result?.state).toBe("审批中");
expect(result?.history.map((entry) => entry.action)).toEqual(["提交送审", "自动同意", "打印单据"]);
expect(result?.history[1]?.operator?.name).toBe("Ebot (智能审批)");
expect(result?.history[2]?.nodeName).toBe("打印提醒");
expect(result?.history[0]?.rawAction).toBe("freeflow.submit");
expect(result?.history[0]?.rawState).toBe("SUBMITTED");
});
it("builds the captured approve, reject, transfer, add-node and comment payloads", async () => {
const calls: Array<{ path: string; options: any }> = [];
const client = {
+67 -37
View File
@@ -3,6 +3,7 @@ import { KyInstance } from "ky";
import { existsSync } from "node:fs";
import { mkdir, writeFile } from "node:fs/promises";
import { basename, extname, join, resolve } from "node:path";
import { getGlobalCache } from "../../core/cache/index.js";
import {
searchRawBills,
getRawBillsByIds,
@@ -23,7 +24,12 @@ import {
type BillActionOptions,
type BillActionTarget,
} from "./api.js";
import type { TranslatorOptions } from "./translator.js";
import {
formatBillFlowOperator,
translateBillFlowAction,
translateBillFlowState,
type TranslatorOptions,
} from "./translator.js";
import {
type RawBillItem,
type FormattedBill,
@@ -93,9 +99,8 @@ const COMMON_FIELD_LABELS: Record<string, string> = {
ownerAndApproverPrintNodeFlag: "节点打印控制标识",
};
// ── 字段元数据内存缓存 ─────────────────────────────────────────────────────────
// ── 字段元数据与关联目录多级缓存 ─────────────────────────────────────────────
const schemaCache = new Map<string, { timestamp: number; dictionary: Map<string, { label: string; type: string }>; entities: EntityMeta[] }>();
const CACHE_TTL_MS = 10 * 60 * 1000; // 10 分钟缓存
type ReferenceCatalog = {
@@ -105,22 +110,20 @@ type ReferenceCatalog = {
feeTypes: Map<string, Record<string, unknown>>;
};
const referenceCatalogCache = new Map<string, ReferenceCatalog>();
export async function getFieldDictionary(
client: KyInstance,
corpId: string,
forceRefresh = false
): Promise<{ dictionary: Map<string, { label: string; type: string }>; entities: EntityMeta[] }> {
const cached = schemaCache.get(corpId);
if (!forceRefresh && cached && Date.now() - cached.timestamp < CACHE_TTL_MS) {
return cached;
}
const cache = getGlobalCache();
const rawEntities = await cache.withCache(
`bill:entities:${corpId}`,
() => listEntitySchemas(client, corpId, { start: 0, count: 100 }),
{ namespace: "bills", ttlMs: CACHE_TTL_MS, forceRefresh }
);
const entities = await listEntitySchemas(client, corpId, { start: 0, count: 100 });
const dictionary = new Map<string, { label: string; type: string }>();
for (const entity of entities) {
for (const entity of rawEntities) {
for (const field of entity.fields) {
if (field.name && field.label) {
dictionary.set(field.name, { label: field.label, type: field.type });
@@ -128,9 +131,7 @@ export async function getFieldDictionary(
}
}
const result = { timestamp: Date.now(), dictionary, entities };
schemaCache.set(corpId, result);
return result;
return { dictionary, entities: rawEntities };
}
function referenceId(value: unknown): string | undefined {
@@ -141,10 +142,14 @@ function referenceId(value: unknown): string | undefined {
}
function referenceObject(value: unknown): Record<string, unknown> | undefined {
return value && typeof value === "object" ? value as Record<string, unknown> : undefined;
return value && typeof value === "object" ? (value as Record<string, unknown>) : undefined;
}
function flattenDepartments(items: Record<string, unknown>[], parentPath = "", output = new Map<string, { item: Record<string, unknown>; path: string }>()): Map<string, { item: Record<string, unknown>; path: string }> {
function flattenDepartments(
items: Record<string, unknown>[],
parentPath = "",
output = new Map<string, { item: Record<string, unknown>; path: string }>()
): Map<string, { item: Record<string, unknown>; path: string }> {
for (const item of items) {
const name = typeof item.name === "string" ? item.name : "";
const path = name ? (parentPath ? `${parentPath}/${name}` : name) : parentPath;
@@ -158,7 +163,10 @@ function flattenDepartments(items: Record<string, unknown>[], parentPath = "", o
return output;
}
function flattenFeeTypes(items: Record<string, unknown>[], output = new Map<string, Record<string, unknown>>()): Map<string, Record<string, unknown>> {
function flattenFeeTypes(
items: Record<string, unknown>[],
output = new Map<string, Record<string, unknown>>()
): Map<string, Record<string, unknown>> {
for (const item of items) {
const feeType = referenceObject(item.feeType) ?? item;
const id = typeof feeType.id === "string" ? feeType.id : undefined;
@@ -172,29 +180,35 @@ function flattenFeeTypes(items: Record<string, unknown>[], output = new Map<stri
}
async function getReferenceCatalog(client: KyInstance, corpId: string): Promise<ReferenceCatalog> {
const cached = referenceCatalogCache.get(corpId);
if (cached && Date.now() - cached.timestamp < CACHE_TTL_MS) return cached;
const [staffs, departments, feeTypes] = await Promise.all([
listActiveStaffCatalog(client, corpId),
getDepartmentTree(client, corpId),
getFeeTypeTree(client, corpId),
]);
const cache = getGlobalCache();
const raw = await cache.withCache(
`bill:ref_raw:${corpId}`,
async () => {
const [staffs, departments, feeTypes] = await Promise.all([
listActiveStaffCatalog(client, corpId),
getDepartmentTree(client, corpId),
getFeeTypeTree(client, corpId),
]);
return { staffs, departments, feeTypes };
},
{ namespace: "bills", ttlMs: CACHE_TTL_MS }
);
const staff = new Map<string, Record<string, unknown>>();
for (const item of staffs) {
for (const item of raw.staffs) {
if (typeof item.id === "string") {
staff.set(item.id, item);
const userId = typeof item.userId === "string" ? item.userId : undefined;
if (userId) staff.set(userId, item);
}
}
const result = {
return {
timestamp: Date.now(),
staff,
departments: flattenDepartments(departments),
feeTypes: flattenFeeTypes(feeTypes),
departments: flattenDepartments(raw.departments),
feeTypes: flattenFeeTypes(raw.feeTypes),
};
referenceCatalogCache.set(corpId, result);
return result;
}
function toReference(
@@ -875,17 +889,30 @@ export async function getBillFlow(
const nextOperators = Array.isArray(log.nextOperatorIds)
? log.nextOperatorIds.map(flowPerson).filter((person): person is NonNullable<typeof person> => Boolean(person))
: [];
const operator = flowPerson(log.operatorId);
const isEbot = attributes.isEbotNode === true || `${operator?.id || ""} ${operator?.name || ""}`.toLowerCase().includes("ebot");
const labeledOperator = isEbot
? { ...(operator || { id: "ebot" }), name: "Ebot (智能审批)" }
: operator;
const rawAction = typeof log.action === "string" ? log.action : undefined;
const rawState = typeof log.state === "string" ? log.state : undefined;
return {
id: typeof log.id === "string" ? log.id : undefined,
time: currentTime,
durationMs,
state: typeof log.state === "string" ? log.state : undefined,
action: typeof log.action === "string" ? log.action : undefined,
nodeName: typeof attributes.nodeName === "string" ? attributes.nodeName : typeof attributes.nextName === "string" ? attributes.nextName : undefined,
state: translateBillFlowState(rawState),
rawState,
action: translateBillFlowAction(rawAction),
rawAction,
nodeName: typeof attributes.nodeName === "string" && attributes.nodeName
? attributes.nodeName
: typeof attributes.nextName === "string" && attributes.nextName
? attributes.nextName
: translateBillFlowAction(rawAction) === "打印单据" ? "打印提醒" : undefined,
comment: typeof attributes.comment === "string" && attributes.comment ? attributes.comment : undefined,
automatic: attributes.isEbotNode === true || attributes.isAuto === true || !log.operatorId,
skipped: attributes.isSkip === true || attributes.skipped === true || log.state === "SKIPPED",
operator: flowPerson(log.operatorId),
operator: labeledOperator,
nextOperators,
};
});
@@ -903,7 +930,7 @@ export async function getBillFlow(
id: typeof node.id === "string" ? node.id : undefined,
name: typeof node.name === "string" ? node.name : undefined,
type: typeof node.type === "string" ? node.type : undefined,
state: typeof node.id === "string" && node.id === nextNodeId || typeof node.name === "string" && node.name === currentNode ? "current" : "planned",
state: typeof node.id === "string" && node.id === nextNodeId || typeof node.name === "string" && node.name === currentNode ? "当前" : "后续",
approver,
approvers,
};
@@ -916,7 +943,7 @@ export async function getBillFlow(
flowId: typeof flow.id === "string" ? flow.id : undefined,
billCode: typeof form.code === "string" ? form.code : undefined,
title: typeof form.title === "string" ? form.title : undefined,
state: typeof raw.state === "string" ? raw.state : typeof flow.state === "string" ? flow.state : undefined,
state: translateBillFlowState(typeof raw.state === "string" ? raw.state : typeof flow.state === "string" ? flow.state : undefined),
currentNode: currentNode ?? (typeof lastAttributes.nextName === "string" ? lastAttributes.nextName : undefined),
history,
pending,
@@ -1425,6 +1452,9 @@ export async function getTranslatorContext(
export {
translateBillFlowToMarkdown,
formatBillFlowOperator,
translateBillFlowAction,
translateBillFlowState,
formatAmountValue,
formatDateValue,
formatPersonValue,
+46
View File
@@ -130,6 +130,52 @@ export interface TranslatorOptions {
datalinkCardMap?: Map<string, string>;
}
const BILL_FLOW_ACTION_LABELS: Record<string, string> = {
"freeflow.submit": "提交送审",
"freeflow.agree": "审批同意",
"freeflow.autoAgree": "自动同意",
"freeflow.reject": "审批驳回",
"freeflow.print": "打印单据",
"freeflow.retract": "单据撤回",
"freeflow.addnode": "加签/转交",
"freeflow.comment": "发表评论",
};
const BILL_FLOW_STATE_LABELS: Record<string, string> = {
APPROVING: "审批中",
APPROVED: "审批通过",
REJECTED: "审批驳回",
REVOKED: "已撤回",
CANCELED: "已取消",
CANCELLED: "已取消",
SKIPPED: "已跳过",
SUBMITTED: "已提交",
PENDING: "待审批",
WAITING: "待处理",
COMPLETED: "已完成",
DRAFT: "草稿",
};
export function translateBillFlowAction(action?: string): string | undefined {
if (!action) return undefined;
return BILL_FLOW_ACTION_LABELS[action] || action;
}
export function translateBillFlowState(state?: string): string | undefined {
if (!state) return undefined;
return BILL_FLOW_STATE_LABELS[state.toUpperCase()] || state;
}
export function formatBillFlowOperator(
operator?: { id?: string; name?: string },
automatic = false,
isEbot = false
): string {
const raw = `${operator?.id || ""} ${operator?.name || ""}`.toLowerCase();
if (isEbot || raw.includes("ebot")) return "Ebot (智能审批)";
return operator?.name || (automatic ? "系统" : "-");
}
// ── 5. 部门全路径格式化 ───────────────────────────────────────────────────────
export function formatDepartmentValue(
+2
View File
@@ -109,7 +109,9 @@ export interface BillFlowEntry {
time?: number;
durationMs?: number;
state?: string;
rawState?: string;
action?: string;
rawAction?: string;
nodeName?: string;
comment?: string;
automatic?: boolean;
+40 -20
View File
@@ -1,37 +1,53 @@
import { z } from "zod";
import type { KyInstance } from "ky";
import { getGlobalCache } from "../../core/cache/index.js";
import { listDimensionCatalogs, listDimensionItems } from "./api.js";
import type { DimensionCatalog, DimensionItem, DimensionQuery } from "./types.js";
const cache = new Map<string, { timestamp: number; catalogs: DimensionCatalog[]; items: Map<string, DimensionItem[]> }>();
const CACHE_TTL_MS = 10 * 60 * 1000;
async function getCached(client: KyInstance, corpId: string): Promise<{ catalogs: DimensionCatalog[]; items: Map<string, DimensionItem[]> }> {
const existing = cache.get(corpId);
if (existing && Date.now() - existing.timestamp < CACHE_TTL_MS) return existing;
const catalogs = await listDimensionCatalogs(client, corpId);
const result = { timestamp: Date.now(), catalogs, items: new Map<string, DimensionItem[]>() };
cache.set(corpId, result);
return result;
async function getCachedCatalogs(client: KyInstance, corpId: string): Promise<DimensionCatalog[]> {
const cache = getGlobalCache();
return cache.withCache(
`dimensions:catalogs:${corpId}`,
() => listDimensionCatalogs(client, corpId),
{ namespace: "dimensions", ttlMs: CACHE_TTL_MS }
);
}
export async function searchDimensions(client: KyInstance, corpId: string, query: DimensionQuery = {}): Promise<DimensionCatalog[]> {
const { catalogs } = await getCached(client, corpId);
export async function searchDimensions(
client: KyInstance,
corpId: string,
query: DimensionQuery = {}
): Promise<DimensionCatalog[]> {
const catalogs = await getCachedCatalogs(client, corpId);
const keyword = (query.name || query.code || query.id || "").trim().toLowerCase();
if (!keyword) return catalogs;
return catalogs.filter((item) => [item.id, item.name, item.code].some((value) => value.toLowerCase().includes(keyword)));
return catalogs.filter((item) =>
[item.id, item.name, item.code].some((value) => value.toLowerCase().includes(keyword))
);
}
export async function getDimensionItems(client: KyInstance, corpId: string, dimension: DimensionCatalog, start = 0, count = 100): Promise<DimensionItem[]> {
const catalog = await getCached(client, corpId);
const cached = catalog.items.get(dimension.id);
if (cached && start === 0 && count >= cached.length) return cached;
const items = await listDimensionItems(client, corpId, dimension.id, start, count);
if (start === 0) catalog.items.set(dimension.id, items);
return items;
export async function getDimensionItems(
client: KyInstance,
corpId: string,
dimension: DimensionCatalog,
start = 0,
count = 100
): Promise<DimensionItem[]> {
const cache = getGlobalCache();
return cache.withCache(
`dimensions:items:${corpId}:${dimension.id}:${start}:${count}`,
() => listDimensionItems(client, corpId, dimension.id, start, count),
{ namespace: "dimensions", ttlMs: CACHE_TTL_MS }
);
}
export async function resolveDimension(client: KyInstance, corpId: string, target: string): Promise<{ dimension: DimensionCatalog; items: DimensionItem[] } | undefined> {
export async function resolveDimension(
client: KyInstance,
corpId: string,
target: string
): Promise<{ dimension: DimensionCatalog; items: DimensionItem[] } | undefined> {
const matches = await searchDimensions(client, corpId, { id: target, code: target, name: target });
const dimension = matches[0];
if (!dimension) return undefined;
@@ -46,7 +62,11 @@ export const dimensionTools = [
handler: async ({ corpContext }: any, params: { keyword?: string; count?: number }) => {
const corp = corpContext.getCurrent();
if (!corp) throw new Error("未配置活跃企业上下文");
const items = await searchDimensions(await import("../../core/auth/ekb.js").then((m) => m.createEkbClient(corp)), corp.corpId || corp.id, { name: params.keyword });
const items = await searchDimensions(
await import("../../core/auth/ekb.js").then((m) => m.createEkbClient(corp)),
corp.corpId || corp.id,
{ name: params.keyword }
);
return { count: items.length, dimensions: items.slice(0, params.count ?? 100) };
},
},
+63 -22
View File
@@ -1,40 +1,81 @@
import { z } from "zod";
import type { KyInstance } from "ky";
import { getGlobalCache } from "../../core/cache/index.js";
import { listRoleGroups, listRoleMembers, listRoles } from "./api.js";
import type { Role, RoleGroup, RoleMemberReport, RoleQuery } from "./types.js";
const cache = new Map<string, { timestamp: number; roles: Role[]; groups: RoleGroup[] }>();
const CACHE_TTL_MS = 10 * 60 * 1000;
async function getCatalog(client: KyInstance, corpId: string): Promise<{ roles: Role[]; groups: RoleGroup[] }> {
const existing = cache.get(corpId);
if (existing && Date.now() - existing.timestamp < CACHE_TTL_MS) return existing;
const [roles, groups] = await Promise.all([listRoles(client, corpId), listRoleGroups(client, corpId)]);
const result = { timestamp: Date.now(), roles, groups }; cache.set(corpId, result); return result;
async function getCatalog(
client: KyInstance,
corpId: string
): Promise<{ roles: Role[]; groups: RoleGroup[] }> {
const cache = getGlobalCache();
return cache.withCache(
`roles:catalog:${corpId}`,
async () => {
const [roles, groups] = await Promise.all([
listRoles(client, corpId),
listRoleGroups(client, corpId),
]);
return { roles, groups };
},
{ namespace: "roles", ttlMs: CACHE_TTL_MS }
);
}
export async function searchRoles(client: KyInstance, corpId: string, query: RoleQuery = {}): Promise<Role[]> {
export async function searchRoles(
client: KyInstance,
corpId: string,
query: RoleQuery = {}
): Promise<Role[]> {
const { roles } = await getCatalog(client, corpId);
const keyword = (query.keyword || query.id || query.code || query.name || "").trim().toLowerCase();
if (!keyword) return roles;
return roles.filter((role) => [role.id, role.name, role.code, role.purposeName, role.scope.name].some((value) => value.toLowerCase().includes(keyword)));
return roles.filter((role) =>
[role.id, role.name, role.code, role.purposeName, role.scope.name].some((value) =>
value.toLowerCase().includes(keyword)
)
);
}
export async function getRoleGroups(client: KyInstance, corpId: string): Promise<RoleGroup[]> { return (await getCatalog(client, corpId)).groups; }
export async function resolveRole(client: KyInstance, corpId: string, target: string): Promise<Role | undefined> {
export async function getRoleGroups(client: KyInstance, corpId: string): Promise<RoleGroup[]> {
return (await getCatalog(client, corpId)).groups;
}
export async function resolveRole(
client: KyInstance,
corpId: string,
target: string
): Promise<Role | undefined> {
const matches = await searchRoles(client, corpId, { keyword: target });
return matches.find((role) => role.id === target || role.code === target || role.name === target) || matches[0];
return (
matches.find((role) => role.id === target || role.code === target || role.name === target) ||
matches[0]
);
}
export async function getRoleMembers(client: KyInstance, corpId: string, target: string): Promise<RoleMemberReport | undefined> {
const role = await resolveRole(client, corpId, target); if (!role) return undefined;
export async function getRoleMembers(
client: KyInstance,
corpId: string,
target: string
): Promise<RoleMemberReport | undefined> {
const role = await resolveRole(client, corpId, target);
if (!role) return undefined;
return { role, members: await listRoleMembers(client, corpId, role.id) };
}
export const roleTools = [{
name: "role_list", description: "列出当前企业角色定义与角色组",
parameters: z.object({ keyword: z.string().optional(), count: z.number().optional() }),
handler: async ({ corpContext }: any, params: { keyword?: string; count?: number }) => {
const corp = corpContext.getCurrent(); if (!corp) throw new Error("未配置活跃企业上下文");
const client = await import("../../core/auth/ekb.js").then((m) => m.createEkbClient(corp));
const roles = await searchRoles(client, corp.corpId || corp.id, { keyword: params.keyword });
return { count: roles.length, roles: roles.slice(0, params.count ?? 100) };
export const roleTools = [
{
name: "role_list",
description: "列出当前企业角色定义与角色组",
parameters: z.object({ keyword: z.string().optional(), count: z.number().optional() }),
handler: async ({ corpContext }: any, params: { keyword?: string; count?: number }) => {
const corp = corpContext.getCurrent();
if (!corp) throw new Error("未配置活跃企业上下文");
const client = await import("../../core/auth/ekb.js").then((m) => m.createEkbClient(corp));
const roles = await searchRoles(client, corp.corpId || corp.id, { keyword: params.keyword });
return { count: roles.length, roles: roles.slice(0, params.count ?? 100) };
},
},
}];
];
+1 -1
View File
@@ -1 +1 @@
export const VERSION = "0.7.4";
export const VERSION = "0.8.0";