Merge pull request #96 from yunyingk/chore/legacy-cleanup
chore(legacy): remove ekb-mcp migration layer and other compat residue
This commit is contained in:
13 files changed
+17
-451
No files matched your search
@@ -1,84 +0,0 @@
|
||||
# 2026-04-06 开发日报
|
||||
|
||||
> 截止提交:`792314a`(日报本身所在提交)
|
||||
> 下一个实例可用 `git log 792314a` 查看全部历史,或 `git checkout 792314a` 还原此状态。
|
||||
|
||||
## 今日目标
|
||||
|
||||
从零搭建 ekb-cli,实现快报智能审核 Agent 的命令行管理,替代图形界面操作。
|
||||
|
||||
---
|
||||
|
||||
## 完成事项
|
||||
|
||||
### 一、项目骨架
|
||||
|
||||
- 初始化 Python 包结构(uv + pyproject.toml)
|
||||
- 实现认证机制:自定义 Header(accesstoken / corpid / staffid),支持多企业存储与切换
|
||||
- 解决 SOCKS5 代理兼容问题(补充 `httpx[socks]` 依赖)
|
||||
|
||||
### 二、ekb auth 命令组
|
||||
|
||||
| 命令 | 功能 |
|
||||
|---|---|
|
||||
| `ekb auth add` | 添加企业认证 |
|
||||
| `ekb auth list` | 列出所有企业 |
|
||||
| `ekb auth use` | 切换当前企业 |
|
||||
| `ekb auth remove` | 删除企业 |
|
||||
| `ekb auth whoami` | 查看当前企业 |
|
||||
|
||||
### 三、ekb agent 命令组
|
||||
|
||||
**Agent 管理**
|
||||
|
||||
| 命令 | 功能 |
|
||||
|---|---|
|
||||
| `ekb agent list` | 列出所有 Agent |
|
||||
| `ekb agent get <id>` | 查看 Agent 详情(含四类条款、关联规则列表) |
|
||||
| `ekb agent get <id> --full` | 不截断规则字段,提示完整文本总字符数 |
|
||||
| `ekb agent update <id>` | patch 式修改(只改传入字段,其余保持原值) |
|
||||
| `ekb agent logs` | 查看审核日志(待实现) |
|
||||
|
||||
**规则管理**
|
||||
|
||||
| 命令 | 功能 |
|
||||
|---|---|
|
||||
| `ekb agent rules` | 列出企业全部审核规则 |
|
||||
| `ekb agent rules --level 严重` | 按风险等级筛选 |
|
||||
| `ekb agent rules --full` | 不截断描述字段 |
|
||||
| `ekb agent rule-get <编码或ID>` | 查看规则详情,含关联 Agent 列表 |
|
||||
|
||||
> 编码输入自适应:`1` / `01` / `0001` / `#0001` 均可识别,自动补零对齐。
|
||||
|
||||
### 四、ekb commands
|
||||
|
||||
`ekb commands` / `ekb commands agent` — 分层展示命令树,引导向下钻取。
|
||||
|
||||
### 五、API 封装(api/agent.py)
|
||||
|
||||
对接接口:
|
||||
|
||||
```
|
||||
GET /api/engine/hab/agent/list
|
||||
GET /api/engine/hab/agent/detail
|
||||
POST /api/engine/hab/agent/save
|
||||
GET /api/engine/hab/agent/rule/list
|
||||
POST /api/engine/hab/agent/rule/save
|
||||
POST /api/engine/hab/agent/rule/update
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 设计决策
|
||||
|
||||
- **截断提示展示字符总数**:CLI 是生产环境唯一入口(无 MCP),AI 读输出时需要知道是否值得拉全量数据,所以截断时提示完整文本总字符数而非截断标准。
|
||||
- **patch 式 update**:先 GET 当前值,再合并传入字段,避免覆盖未传字段。
|
||||
- **文档分层**:`CLAUDE.md`(项目级全图)→ `README.agent.md`(agent 语义/常量)→ `README.rule.md`(rule 语义/常量)。枚举常量不写在顶层文件。
|
||||
|
||||
---
|
||||
|
||||
## 待办
|
||||
|
||||
- [ ] `ekb agent logs` — 需抓包确认 API 结构
|
||||
- [ ] 规则关联管理 — 给 Agent 增删关联规则(`ruleIds` 字段)
|
||||
- [ ] `ekb rule update` — 修改规则内容(API 已封装,命令未实现)
|
||||
@@ -1,72 +0,0 @@
|
||||
# 2026-04-08 开发日报
|
||||
|
||||
> 截止提交:`c041966`(日报本身所在提交)
|
||||
> 下一个实例可用 `git log c041966` 查看全部历史,或 `git checkout c041966` 还原此状态。
|
||||
|
||||
## 今日目标
|
||||
|
||||
在昨日基础上扩展写操作命令,完善 API 层架构。
|
||||
|
||||
---
|
||||
|
||||
## 完成事项
|
||||
|
||||
### 一、新增写操作命令
|
||||
|
||||
**规则管理**
|
||||
|
||||
| 命令 | 功能 |
|
||||
|---|---|
|
||||
| `ekb agent rule-create` | 新建审核规则(`--purpose` / `--desc` / `--level`) |
|
||||
|
||||
**Agent 管理**
|
||||
|
||||
| 命令 | 功能 |
|
||||
|---|---|
|
||||
| `ekb agent create` | 新建 Agent(支持全部字段,含关联规则 ID) |
|
||||
| `ekb agent copy <id>` | 复制 Agent,名称自动追加「(副本)」,检测重名 |
|
||||
| `ekb agent delete <id>` | 删除 Agent,方向键交互确认,不可恢复 |
|
||||
|
||||
### 二、API 层重构
|
||||
|
||||
- **拆分文件**:`api/agent.py`(Agent 接口)+ `api/rule.py`(Rule 接口)+ `api/schemas.py`(Pydantic 模型)
|
||||
- **统一 re-export**:所有 commands 只从 `ekb_cli.api` 导入,内部拆分对上层透明
|
||||
- **引入 Pydantic 校验**:所有接口响应经 `model_validate` 强制校验,字段变更时抛 `ValidationError` 精确定位,而非静默返回空值
|
||||
- 新增接口:`GET /engine/hab/agent/checkName`、`GET /engine/hab/agent/active`
|
||||
|
||||
### 三、交互体验优化
|
||||
|
||||
- `ekb agent delete` 默认使用 `questionary` 方向键选择器,默认停在「取消」
|
||||
- 非 tty 环境(管道/AI调用)自动降级为 `y/N` 文字输入;`--ai` 参数可强制指定;`--yes` 跳过确认
|
||||
- 修复 `checkName` 接口语义反转 bug(`data=false` 表示名称可用)
|
||||
|
||||
### 四、文档补全
|
||||
|
||||
- 新增 `api/README.api.md`:三层架构说明、各接口签名、Pydantic 应对策略
|
||||
- 补全 `README.agent.md`:`state` 枚举含义(0=启用 / 1=禁用 / 2=已删除)及对应接口
|
||||
- 补全 `README.rule.md`:`rule-create` 命令速查
|
||||
|
||||
---
|
||||
|
||||
## 新增接口
|
||||
|
||||
```
|
||||
GET /api/engine/hab/agent/checkName?name=xxx # 检查名称唯一性(data=false 表示可用)
|
||||
GET /api/engine/hab/agent/active?id=xxx&state= # 变更 Agent 状态(0启用/1禁用/2删除)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 设计决策
|
||||
|
||||
- **"删除"是状态变更**:快报无真正的 DELETE 接口,`state=2` 即为删除,通过 `/active` 接口实现。
|
||||
- **Pydantic `extra="allow"`**:允许快报新增字段,但已知字段强制类型,兼顾前向兼容与变更感知。
|
||||
- **`questionary` 仅在 tty 下启用**:`sys.stdin.isatty()` 自动检测,无需用户关心环境差异。
|
||||
|
||||
---
|
||||
|
||||
## 待办
|
||||
|
||||
- [ ] `ekb agent logs` — 需抓包确认 API 结构
|
||||
- [ ] `ekb agent rule update` — 修改规则内容(API 已封装,命令未实现)
|
||||
- [ ] `ekb agent rule delete` — 删除规则(接口待确认)
|
||||
@@ -1,107 +0,0 @@
|
||||
# 2026-05-18 开发日报
|
||||
|
||||
> 截止提交:`298e114`(当前 feature/workflow-control 分支)
|
||||
> 下一个实例可用 `git log 298e114` 查看全部历史,或 `git checkout 298e114` 还原此状态。
|
||||
|
||||
## 今日目标
|
||||
|
||||
讨论并确定 ekb-mcp 项目的数据库方案。
|
||||
|
||||
---
|
||||
|
||||
## 讨论内容
|
||||
|
||||
### 一、数据库选型分析
|
||||
|
||||
**时间:2026-05-18 18:30**
|
||||
|
||||
针对项目是否需要数据库进行了深入讨论:
|
||||
|
||||
| 方案 | 优点 | 缺点 | 适用场景 |
|
||||
|------|------|------|----------|
|
||||
| PostgreSQL | 功能强大,支持复杂查询和并发 | 需要额外部署,运维复杂 | 多用户并发,复杂查询 |
|
||||
| SQLite | 轻量级,嵌入式,无需额外服务 | 并发支持有限 | 单机部署,小规模应用 |
|
||||
| 内存缓存 + JSON 文件 | 简单,无依赖,性能最高 | 重启后缓存丢失 | 单实例,数据量小 |
|
||||
|
||||
### 二、项目特点分析
|
||||
|
||||
**当前状态:**
|
||||
- 配置存储在 `enterprises/*.json` 文件中
|
||||
- 企业配置数量少(几个到几十个)
|
||||
- 结构简单,只需按 ID 读取
|
||||
- MCP 服务器单实例运行
|
||||
|
||||
**性能问题:**
|
||||
- `loadCorpConfigs()` 每次调用都读取文件系统
|
||||
- `getCorpTokens()` 每次调用都读取文件系统
|
||||
- 没有任何缓存机制
|
||||
- 大量重复查询会导致频繁的文件 I/O
|
||||
|
||||
### 三、中间件方案讨论
|
||||
|
||||
**时间:2026-05-18 19:00**
|
||||
|
||||
曾考虑实现存储中间件(Repository 模式),支持多种存储后端:
|
||||
|
||||
```
|
||||
src/core/storage/
|
||||
├── types.ts # 接口定义
|
||||
├── memory.ts # 内存存储实现
|
||||
├── sqlite.ts # SQLite 实现
|
||||
├── postgres.ts # PostgreSQL 实现
|
||||
└── factory.ts # 工厂函数
|
||||
```
|
||||
|
||||
**反思:**
|
||||
- 过度设计:对于当前项目来说太复杂
|
||||
- 维护成本:需要维护多个存储后端的代码
|
||||
- 依赖管理:需要处理可选依赖
|
||||
- 学习成本:新开发者需要理解抽象层
|
||||
|
||||
### 四、最终决策
|
||||
|
||||
**时间:2026-05-18 19:30**
|
||||
|
||||
**选择方案:内存缓存 + JSON 文件**
|
||||
|
||||
**理由:**
|
||||
1. **数据量小** - 企业配置通常不多,文件足够
|
||||
2. **结构简单** - 不需要复杂查询,只需按 ID 读取
|
||||
3. **运维简单** - 无额外依赖,易于备份和版本控制
|
||||
4. **单实例运行** - MCP 服务器通常单实例,无需高并发支持
|
||||
5. **性能足够** - 内存缓存可以解决重复查询的性能问题
|
||||
|
||||
**实现方案:**
|
||||
```typescript
|
||||
// 简单的内存缓存
|
||||
const cache = new Map<string, CorpConfig>();
|
||||
|
||||
function getConfig(id: string): CorpConfig | undefined {
|
||||
if (cache.has(id)) return cache.get(id);
|
||||
const config = loadFromFile(id);
|
||||
if (config) cache.set(id, config);
|
||||
return config;
|
||||
}
|
||||
```
|
||||
|
||||
**清理工作:**
|
||||
- 移除了 `src/core/storage/` 目录(过度设计的中间件方案)
|
||||
- 移除了 `scripts/migrate-configs.ts`(不再需要的迁移脚本)
|
||||
|
||||
---
|
||||
|
||||
## 后续计划
|
||||
|
||||
1. 实现内存缓存机制,解决重复查询的性能问题
|
||||
2. 保持现有 JSON 文件方案,简化架构
|
||||
3. 如果未来数据量增长,再考虑 SQLite 作为轻量级方案
|
||||
|
||||
---
|
||||
|
||||
## 技术笔记
|
||||
|
||||
- 项目使用 TypeScript + Bun 运行时
|
||||
- 配置文件位于 `enterprises/*.json`
|
||||
- Token 缓存位于 `~/.cache/ekb-mcp/tokens.json`
|
||||
- 当前分支:`feature/workflow-control`
|
||||
- 最新提交:`298e114` - feat(platform): 新增工作流控制及辅助工具
|
||||
@@ -39,7 +39,6 @@ describe("dev hygiene tooling", () => {
|
||||
unreachableCommits: ["deadbeef"],
|
||||
skill: {} as any,
|
||||
binaries: [],
|
||||
legacyConfig: {} as any,
|
||||
};
|
||||
const plan = buildCleanupPlan(snapshot, false);
|
||||
expect(plan.map((action) => action.target)).toEqual(["/tmp/merged", "feat/merged"]);
|
||||
|
||||
@@ -90,12 +90,6 @@ interface HygieneSnapshot {
|
||||
matches: boolean;
|
||||
error?: string;
|
||||
}>;
|
||||
legacyConfig: {
|
||||
enterprisesDir: string;
|
||||
configFile: string;
|
||||
enterprisesDirExists: boolean;
|
||||
configFileExists: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
export interface HygieneReport {
|
||||
@@ -304,13 +298,6 @@ function inspectBinary(name: string): HygieneSnapshot["binaries"][number] {
|
||||
}
|
||||
}
|
||||
|
||||
function parseLegacyConfig(): HygieneSnapshot["legacyConfig"] {
|
||||
const home = homedir();
|
||||
const enterprisesDir = join(home, ".cache", "ekb-mcp", "enterprises");
|
||||
const configFile = join(home, ".cache", "ekb-mcp", "config.json");
|
||||
return { enterprisesDir, configFile, enterprisesDirExists: existsSync(enterprisesDir), configFileExists: existsSync(configFile) };
|
||||
}
|
||||
|
||||
function collectSnapshot(): HygieneSnapshot {
|
||||
return {
|
||||
repository: parseRepository(),
|
||||
@@ -319,7 +306,6 @@ function collectSnapshot(): HygieneSnapshot {
|
||||
unreachableCommits: parseUnreachableCommits(),
|
||||
skill: parseSkill(),
|
||||
binaries: [inspectBinary("hose-use"), inspectBinary("hose-aipro")],
|
||||
legacyConfig: parseLegacyConfig(),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -370,10 +356,6 @@ function buildFindings(snapshot: HygieneSnapshot): Finding[] {
|
||||
findings.push({ id: "binary.drift", level: "warning", message: `${binary.name} 全局版本与当前源码不一致`, details: binary, nextAction: "运行 bun run dev:override 同步全局开发版" });
|
||||
}
|
||||
}
|
||||
const legacy = snapshot.legacyConfig;
|
||||
if (legacy.enterprisesDirExists || legacy.configFileExists) {
|
||||
findings.push({ id: "config.legacy", level: "warning", message: "发现旧版 ekb-mcp 配置路径;检查不会删除配置", details: legacy, nextAction: "先确认迁移结果,再按配置迁移策略清理" });
|
||||
}
|
||||
return findings;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||||
import { runAiProCli } from "./aipro-cli.js";
|
||||
import { closeApprovalDatabase, getApprovalDatabase } from "./domains/approval/db.js";
|
||||
import { closeDatabase, getDatabase } from "./core/db/index.js";
|
||||
import { ApprovalRepository } from "./domains/approval/repository.js";
|
||||
import { getVersionInfo } from "./version.js";
|
||||
|
||||
describe("CLI - hose-aipro 审批流与网关阻拦全链路测试", () => {
|
||||
beforeEach(() => {
|
||||
process.env.HOSE_APPROVAL_DB = ":memory:";
|
||||
const db = getApprovalDatabase(":memory:");
|
||||
const db = getDatabase(":memory:");
|
||||
const repo = new ApprovalRepository(db);
|
||||
|
||||
// 预置规约规则
|
||||
@@ -22,7 +22,7 @@ describe("CLI - hose-aipro 审批流与网关阻拦全链路测试", () => {
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
closeApprovalDatabase();
|
||||
closeDatabase();
|
||||
delete process.env.HOSE_APPROVAL_DB;
|
||||
});
|
||||
|
||||
@@ -37,7 +37,7 @@ describe("CLI - hose-aipro 审批流与网关阻拦全链路测试", () => {
|
||||
});
|
||||
|
||||
test("完整闭环:bind 挂载 ➔ review 证据核验 ➔ decide 网关阻拦与裁决 ➔ logs 审计追溯", async () => {
|
||||
const db = getApprovalDatabase(":memory:");
|
||||
const db = getDatabase(":memory:");
|
||||
const repo = new ApprovalRepository(db);
|
||||
|
||||
// 1. 创建审批会话
|
||||
@@ -125,7 +125,7 @@ describe("CLI - hose-aipro 审批流与网关阻拦全链路测试", () => {
|
||||
});
|
||||
|
||||
test("门禁防御:单据无硬性或弹性违规时,尝试执行 reject 必须被网关阻断(禁止无因驳回)", async () => {
|
||||
const db = getApprovalDatabase(":memory:");
|
||||
const db = getDatabase(":memory:");
|
||||
const repo = new ApprovalRepository(db);
|
||||
|
||||
const run = repo.createApprovalRun({
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||||
import { runCli } from "../runner.js";
|
||||
import { runAiProCli } from "../../aipro-cli.js";
|
||||
import { closeApprovalDatabase, getApprovalDatabase } from "../../domains/approval/db.js";
|
||||
import { closeDatabase, getDatabase } from "../../core/db/index.js";
|
||||
import { ApprovalRepository } from "../../domains/approval/repository.js";
|
||||
|
||||
describe("CLI - 上下文自省与 AI PRO 状态命令 (Zero-Source-Reading Context)", () => {
|
||||
beforeEach(() => {
|
||||
process.env.HOSE_APPROVAL_DB = ":memory:";
|
||||
const db = getApprovalDatabase(":memory:");
|
||||
const db = getDatabase(":memory:");
|
||||
const repo = new ApprovalRepository(db);
|
||||
|
||||
repo.createRule({
|
||||
@@ -21,7 +21,7 @@ describe("CLI - 上下文自省与 AI PRO 状态命令 (Zero-Source-Reading Cont
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
closeApprovalDatabase();
|
||||
closeDatabase();
|
||||
delete process.env.HOSE_APPROVAL_DB;
|
||||
});
|
||||
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||||
import { runCli } from "../runner.js";
|
||||
import { closeApprovalDatabase, getApprovalDatabase } from "../../domains/approval/db.js";
|
||||
import { closeDatabase, getDatabase } from "../../core/db/index.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 db = getDatabase(":memory:");
|
||||
const repo = new ApprovalRepository(db);
|
||||
|
||||
// 预置几条测试规则 (仅需 适用场景 + 规约正文 两个要素)
|
||||
@@ -25,7 +25,7 @@ describe("CLI - hose-use rule 规则与场景索引命令", () => {
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
closeApprovalDatabase();
|
||||
closeDatabase();
|
||||
delete process.env.HOSE_APPROVAL_DB;
|
||||
});
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||||
import { mkdtempSync, mkdirSync, rmSync, writeFileSync, existsSync, readFileSync, statSync, utimesSync } from "node:fs";
|
||||
import { mkdtempSync, mkdirSync, rmSync, writeFileSync, existsSync, readFileSync, statSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import {
|
||||
@@ -11,8 +11,6 @@ import {
|
||||
loadGlobalConfig,
|
||||
saveGlobalConfig,
|
||||
resolveGlobalConfigFile,
|
||||
syncLegacyEnterprisesDir,
|
||||
syncLegacyGlobalConfig,
|
||||
} from "./loader.js";
|
||||
import { saveAccount, loadAccountStore, resolveAccountCachePath } from "../auth/account-store.js";
|
||||
import type { CorpConfig } from "./types.js";
|
||||
@@ -174,47 +172,6 @@ describe("core/config/loader", () => {
|
||||
expect(updated.defaultCorpId).toBe("test-corp-123");
|
||||
});
|
||||
|
||||
test("syncLegacyEnterprisesDir copies legacy credentials and removes stale legacy directory", () => {
|
||||
const primary = join(tempDir, "primary");
|
||||
const legacy = join(tempDir, "legacy");
|
||||
mkdirSync(legacy, { recursive: true });
|
||||
writeFileSync(join(legacy, "corp-old.json"), JSON.stringify(createMockCorp("corp-old", "旧企业")));
|
||||
const old = new Date(Date.now() - 10 * 24 * 60 * 60 * 1000);
|
||||
utimesSync(join(legacy, "corp-old.json"), old, old);
|
||||
utimesSync(legacy, old, old);
|
||||
|
||||
const result = syncLegacyEnterprisesDir(primary, legacy);
|
||||
expect(result.copied).toEqual(["corp-old.json"]);
|
||||
expect(result.deletedLegacyDir).toBe(true);
|
||||
expect(existsSync(join(primary, "corp-old.json"))).toBe(true);
|
||||
expect(existsSync(legacy)).toBe(false);
|
||||
});
|
||||
|
||||
test("syncLegacyEnterprisesDir preserves a recently modified legacy directory", () => {
|
||||
const primary = join(tempDir, "primary-recent");
|
||||
const legacy = join(tempDir, "legacy-recent");
|
||||
mkdirSync(legacy, { recursive: true });
|
||||
writeFileSync(join(legacy, "corp-recent.json"), JSON.stringify(createMockCorp("corp-recent", "近期企业")));
|
||||
|
||||
const result = syncLegacyEnterprisesDir(primary, legacy);
|
||||
expect(result.deletedLegacyDir).toBe(false);
|
||||
expect(existsSync(legacy)).toBe(true);
|
||||
});
|
||||
|
||||
test("syncLegacyGlobalConfig migrates and removes a stale legacy config", () => {
|
||||
const primary = join(tempDir, "config", "config.json");
|
||||
const legacy = join(tempDir, "legacy-config.json");
|
||||
writeFileSync(legacy, JSON.stringify({ stateful: false }));
|
||||
const old = new Date(Date.now() - 10 * 24 * 60 * 60 * 1000);
|
||||
utimesSync(legacy, old, old);
|
||||
|
||||
const result = syncLegacyGlobalConfig(primary, legacy);
|
||||
expect(result.copied).toBe(true);
|
||||
expect(result.deletedLegacyFile).toBe(true);
|
||||
expect(JSON.parse(readFileSync(primary, "utf8")).stateful).toBe(false);
|
||||
expect(existsSync(legacy)).toBe(false);
|
||||
});
|
||||
|
||||
test("saveCorpConfig and saveAccount enforce 0o600 file permissions and respect HOSE_ACCOUNTS_FILE", () => {
|
||||
const targetDir = join(tempDir, "secure-corps");
|
||||
const corpFile = saveCorpConfig(createMockCorp("sec-1", "安全测试企业"), targetDir);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { chmodSync, copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
|
||||
import { chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
import { CorpConfig, CorpConfigSchema, GlobalConfig, GlobalConfigSchema, normalizeCorpConfig } from "./types.js";
|
||||
@@ -8,13 +8,9 @@ const USER_DIR_ENV = "HOSE_USER_ENTERPRISES_DIR";
|
||||
const GLOBAL_CONFIG_ENV = "HOSE_CONFIG_FILE";
|
||||
|
||||
export const PRIMARY_USER_ENTERPRISES_DIR = join(homedir(), ".config", "hose-use", "enterprises");
|
||||
export const LEGACY_USER_ENTERPRISES_DIR = join(homedir(), ".cache", "ekb-mcp", "enterprises");
|
||||
export const USER_ENTERPRISES_DIR = PRIMARY_USER_ENTERPRISES_DIR;
|
||||
|
||||
export const PRIMARY_GLOBAL_CONFIG_FILE = join(homedir(), ".config", "hose-use", "config.json");
|
||||
export const LEGACY_GLOBAL_CONFIG_FILE = join(homedir(), ".cache", "ekb-mcp", "config.json");
|
||||
|
||||
const LEGACY_CLEANUP_GRACE_MS = 7 * 24 * 60 * 60 * 1000;
|
||||
|
||||
function ensureDir(dir: string): void {
|
||||
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
||||
@@ -40,14 +36,7 @@ export function resolveEnterprisesDirs(): string[] {
|
||||
const configuredUserDir = process.env[USER_DIR_ENV]?.trim();
|
||||
const userDirs = configuredUserDir
|
||||
? (existsSync(configuredUserDir) ? [configuredUserDir] : [])
|
||||
: (() => {
|
||||
try {
|
||||
syncLegacyEnterprisesDir();
|
||||
} catch {
|
||||
// Legacy migration must never prevent normal CLI startup.
|
||||
}
|
||||
return [PRIMARY_USER_ENTERPRISES_DIR, LEGACY_USER_ENTERPRISES_DIR];
|
||||
})();
|
||||
: [PRIMARY_USER_ENTERPRISES_DIR];
|
||||
|
||||
const globalConfig = loadGlobalConfig();
|
||||
const testDir = globalConfig.testEnterprisesDir?.trim();
|
||||
@@ -82,77 +71,15 @@ export function getEnterprisesDirCandidates(): string[] {
|
||||
`${CONFIG_ENV}=<path>`,
|
||||
...(testDir ? [`testEnterprisesDir: ${testDir}`] : []),
|
||||
PRIMARY_USER_ENTERPRISES_DIR,
|
||||
LEGACY_USER_ENTERPRISES_DIR,
|
||||
];
|
||||
}
|
||||
|
||||
export function resolveGlobalConfigFile(): string {
|
||||
const configured = process.env[GLOBAL_CONFIG_ENV]?.trim();
|
||||
if (configured) return configured;
|
||||
try {
|
||||
syncLegacyGlobalConfig();
|
||||
} catch {
|
||||
// Legacy migration must never prevent normal CLI startup.
|
||||
}
|
||||
if (existsSync(PRIMARY_GLOBAL_CONFIG_FILE)) return PRIMARY_GLOBAL_CONFIG_FILE;
|
||||
if (existsSync(LEGACY_GLOBAL_CONFIG_FILE)) return LEGACY_GLOBAL_CONFIG_FILE;
|
||||
return PRIMARY_GLOBAL_CONFIG_FILE;
|
||||
}
|
||||
|
||||
export function syncLegacyEnterprisesDir(
|
||||
primaryDir: string = PRIMARY_USER_ENTERPRISES_DIR,
|
||||
legacyDir: string = LEGACY_USER_ENTERPRISES_DIR
|
||||
): { copied: string[]; deletedLegacyDir: boolean } {
|
||||
if (!existsSync(legacyDir)) return { copied: [], deletedLegacyDir: false };
|
||||
|
||||
mkdirSync(primaryDir, { recursive: true, mode: 0o700 });
|
||||
const copied: string[] = [];
|
||||
const files = readdirSync(legacyDir).filter((file) => file.endsWith(".json"));
|
||||
|
||||
for (const file of files) {
|
||||
const legacyPath = join(legacyDir, file);
|
||||
const primaryPath = join(primaryDir, file);
|
||||
if (!existsSync(primaryPath) || statSync(legacyPath).mtimeMs > statSync(primaryPath).mtimeMs) {
|
||||
copyFileSync(legacyPath, primaryPath);
|
||||
copied.push(file);
|
||||
}
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const hasRecentEntry = readdirSync(legacyDir).some((file) => now - statSync(join(legacyDir, file)).mtimeMs < LEGACY_CLEANUP_GRACE_MS);
|
||||
const hasNewerLegacyFile = files.some((file) => {
|
||||
const legacyPath = join(legacyDir, file);
|
||||
const primaryPath = join(primaryDir, file);
|
||||
return existsSync(primaryPath) && statSync(legacyPath).mtimeMs > statSync(primaryPath).mtimeMs;
|
||||
});
|
||||
const directoryIsRecent = now - statSync(legacyDir).mtimeMs < LEGACY_CLEANUP_GRACE_MS;
|
||||
const deletedLegacyDir = !hasRecentEntry && !hasNewerLegacyFile && !directoryIsRecent;
|
||||
if (deletedLegacyDir) rmSync(legacyDir, { recursive: true, force: true });
|
||||
return { copied, deletedLegacyDir };
|
||||
}
|
||||
|
||||
export function syncLegacyGlobalConfig(
|
||||
primaryFile: string = PRIMARY_GLOBAL_CONFIG_FILE,
|
||||
legacyFile: string = LEGACY_GLOBAL_CONFIG_FILE
|
||||
): { copied: boolean; deletedLegacyFile: boolean } {
|
||||
if (!existsSync(legacyFile)) return { copied: false, deletedLegacyFile: false };
|
||||
mkdirSync(dirname(primaryFile), { recursive: true, mode: 0o700 });
|
||||
|
||||
let copied = false;
|
||||
if (!existsSync(primaryFile) || statSync(legacyFile).mtimeMs > statSync(primaryFile).mtimeMs) {
|
||||
copyFileSync(legacyFile, primaryFile);
|
||||
copied = true;
|
||||
}
|
||||
|
||||
const oldEnough = Date.now() - statSync(legacyFile).mtimeMs >= LEGACY_CLEANUP_GRACE_MS;
|
||||
const safeToDelete = existsSync(primaryFile) && statSync(legacyFile).mtimeMs <= statSync(primaryFile).mtimeMs && oldEnough;
|
||||
if (safeToDelete) {
|
||||
rmSync(legacyFile, { force: true });
|
||||
return { copied, deletedLegacyFile: true };
|
||||
}
|
||||
return { copied, deletedLegacyFile: false };
|
||||
}
|
||||
|
||||
export function loadGlobalConfig(): GlobalConfig {
|
||||
const file = resolveGlobalConfigFile();
|
||||
try {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Database } from "bun:sqlite";
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||||
import { closeApprovalDatabase, getApprovalDatabase } from "./db.js";
|
||||
import { closeDatabase, getDatabase } from "../../core/db/index.js";
|
||||
import { ApprovalRepository } from "./repository.js";
|
||||
import { ApprovalService } from "./service.js";
|
||||
import { ApprovalRuleValidationError } from "./types.js";
|
||||
@@ -11,12 +11,12 @@ describe("Approval Domain - SQLite 持久化与规约仓储", () => {
|
||||
|
||||
beforeEach(() => {
|
||||
// 每次测试使用独立的内存数据库,隔离状态
|
||||
db = getApprovalDatabase(":memory:");
|
||||
db = getDatabase(":memory:");
|
||||
repo = new ApprovalRepository(db);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
closeApprovalDatabase();
|
||||
closeDatabase();
|
||||
});
|
||||
|
||||
test("数据库初始化时自动种子化默认偏好配置", () => {
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
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 = DEFAULT_DB_PATH;
|
||||
|
||||
export function resolveApprovalDbPath(): string {
|
||||
return resolveDatabasePath();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取或创建 SQLite 数据库连接单例(兼容原接口,底层使用 core/db)
|
||||
*/
|
||||
export function getApprovalDatabase(customPath?: string): Database {
|
||||
return getDatabase(customPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* 关闭并清理当前数据库连接
|
||||
*/
|
||||
export function closeApprovalDatabase(): void {
|
||||
closeDatabase();
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化表结构与默认数据(兼容原接口,委托给 runMigrations)
|
||||
*/
|
||||
export function initDatabaseSchema(db: Database): void {
|
||||
runMigrations(db);
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
export * from "./types.js";
|
||||
export * from "./parser.js";
|
||||
export * from "./db.js";
|
||||
export * from "./repository.js";
|
||||
export * from "./service.js";
|
||||
export * from "./gateway.js";
|
||||
Reference in new issue
Block a user