Compare commits

..
10 Commits
Author SHA1 Message Date
yunyingk 634f0e2b78 Merge pull request #279 from yunyingk/codex/release-v0.11.19
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Canceled after 0s
🚀 Release / 🚀 Build & Publish GitHub Release (push) Canceled after 0s
Release v0.11.19: Automated release bump
2026-11-06 15:03:31 +08:00
gitea 9ec46b244e Release v0.11.19: Automated release bump 2026-11-06 15:02:15 +08:00
yunyingk cb07fad536 Merge pull request #278 from yunyingk/mac15/official-rules-export
feat: 增加 SealAI 官方规则 CSV 导出
2026-11-06 15:01:42 +08:00
gitea f454d62be1 feat: 增加 SealAI 官方规则 CSV 导出 2026-11-06 15:00:05 +08:00
yunyingk 382fc1a7ae Merge pull request #277 from yunyingk/codex/release-v0.11.18
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
🚀 Release / 🚀 Build & Publish GitHub Release (push) Has been cancelled
Release v0.11.18: Automated release bump
2026-11-02 15:26:39 +08:00
gitea a5b504d7a3 Release v0.11.18: Automated release bump 2026-11-02 15:25:42 +08:00
yunyingk 0a1eb015fb Merge pull request #276 from yunyingk/mac15/sqlite-review-and-auth-session-pool
feat: 原生 Seal 授权续期自愈与本地 SQLite 分歧待办闭环
2026-11-02 15:24:20 +08:00
gitea 8c9f102931 feat: 原生 Seal 授权续期自愈与本地 SQLite 分歧待办闭环
- 授权自愈: 引入长效会话 Cookie 备份池,支持 Seal 原生协助授权到期与 401 报错时平滑自动换发与静默续期;
- 存储升级: 审核报告人工裁决底座迁移至 SQLite (~/.config/seal-use/state/reviews.sqlite),支持历史 JSONL 自动平滑导入与向后兼容双写;
- 分歧待办: 新增 report review unreviewed 与 dismiss 命令,收集人机不一致单据并在日常企业命令完成后于 stderr 注入 Agent 动作指引;
- 精密频控: 实现 30 天单据时效窗口过滤(陈年单据自动归档)、动态 5 小时滑动窗口频控与 24 小时人工拒审静音抑制协议;
- 透明认知: 全面补充 Skill 路由与帮助手册,消除黑盒,透传数据边界与安全红线。
2026-11-02 15:22:47 +08:00
yunyingk 5c46c9bcc4 Merge pull request #275 from yunyingk/mac15/fix-update-clean-test-isolation
test(update): 为 cleanStaleBinaries 增加临时目录沙箱隔离
2026-10-29 15:50:15 +08:00
gitea a885d1478e test(update): 为 cleanStaleBinaries 增加临时目录沙箱隔离
在 `src/cli/commands/update.ts` 中为 `cleanStaleBinaries` 增加可选的 `candidateOverrides` 参数,允许在单元测试中注入沙箱路径。
在 `src/cli/commands/update.test.ts` 中重构单测,使用 `mkdtempSync` 创建临时隔离文件测试活跃路径保留与废弃文件清理逻辑,杜绝在宿主机测试期间误伤或删除真实全局二进制。
2026-10-29 15:48:34 +08:00
36 changed files with 1858 additions and 73 deletions

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "seal-use",
"version": "0.11.17",
"version": "0.11.19",
"description": "Seal Use tenant operations: approval-run diagnosis, minimal rule remediation, delegation links, Hose/合思 authorization, users, rules, billing, and search.",
"author": {
"name": "yingqing"
+16
View File
@@ -7,6 +7,22 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [0.11.19] - 2026-11-06
### Added
- Merge pull request #278 from yunyingk/mac15/official-rules-export
- feat: 增加 SealAI 官方规则 CSV 导出
## [0.11.18] - 2026-11-02
### Added
- Merge pull request #276 from yunyingk/mac15/sqlite-review-and-auth-session-pool
- feat: 原生 Seal 授权续期自愈与本地 SQLite 分歧待办闭环
- Merge pull request #275 from yunyingk/mac15/fix-update-clean-test-isolation
- test(update): 为 cleanStaleBinaries 增加临时目录沙箱隔离
## [0.11.17] - 2026-10-29
### Added
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "seal-use",
"version": "0.11.17",
"version": "0.11.19",
"private": true,
"description": "Seal tenant operations toolkit: approval-run diagnosis, rule remediation, Hose/合思 auth, plus a CLI and an optional MCP server.",
"license": "MIT",
+5 -4
View File
@@ -1,9 +1,9 @@
---
name: seal-use
description: "v0.11.17: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."
description: "v0.11.19: Use for Seal Use enterprise onboarding, Hose/合思 or Seal-native authentication, approval operations, diagnosis, simulation, rules, users, configuration, and search."
metadata:
version: 0.11.17
short-description: Seal tenant and Hose approval automation (v0.11.17)
version: 0.11.19
short-description: Seal tenant and Hose approval automation (v0.11.19)
---
# Seal Use
@@ -147,6 +147,7 @@ seal-use langfuse observation <traceId> <observationId> # 最后才取焦点
| 第一次接入、不会找凭据、需要截图 | `references/first-time-user.md` | 用户交付材料后,再读 `enterprise-onboarding.md` 做来源决策 |
| 判断材料来源、Token 边界、cURL、Hose 提权 | `references/enterprise-onboarding.md` | 需要具体域名/员工探测时,再读 `hose-enterprise-init.md` |
| Hose 登录检查、认证失败、合思/Seal 协助链接及登录人员身份 | `references/hose-enterprise-auth.md` | 需要重新接入或判断材料类型时,先读 `enterprise-onboarding.md` |
| SealAI 浏览器会话回放、RUM telemetry 接口 | `references/sealai-browser-rum.md` | 仅在排查浏览器录制/回放采集时读取;不要用于审核业务数据导出 |
| Hose 域名探测、角色/员工发现、管理员选择 | `references/hose-enterprise-init.md` | 不要先加载部署或规则文档 |
| 配置、同步或排查发布到 HoseCloud | `references/hose-enterprise-deploy.md` | 涉及生产/测试配对或模拟时,再读 `staging-simulation-workflow.md` |
| 生产草稿、测试同步、模拟、回归、发布 | `references/staging-simulation-workflow.md` | 需要客诉证据定界时,再读 `customer-feedback-rule-remediation.md` |
@@ -162,6 +163,6 @@ seal-use langfuse observation <traceId> <observationId> # 最后才取焦点
| Langfuse trace 检索、observation IO、session 大纲、规则/附件流追踪 | `references/langfuse-trace.md` | 已定位到 trace 后需要附件归因时,再读 `approval-attachment-trace.md` |
| 附件、发票、收据、OCR 或界面高亮结论争议 | `references/approval-attachment-trace.md` | 先完成追踪和归因后,才读 `approval-bad-cases.md` 做案例对照 |
| 已完成当前追踪后的相似坏案例对照 | `references/approval-bad-cases.md` | 不能作为首次诊断入口 |
| AI 审核报告、验收报告、上线报告、周期准确率报告、accuracy report、台账自由裁量 | `references/report-templates.md` | 只查 CLI 语法时读 `cli.md`;涉及完整报告编制、Excel 台账自由裁量、人机研讨与门禁校验时读取 |
| AI 审核报告、验收报告、上线报告、周期准确率报告、accuracy report、台账自由裁量、人机分歧日常复核与静音协议 | `references/report-templates.md` | 只查 CLI 语法时读 `cli.md`;涉及完整报告编制、Excel 台账自由裁量、人机研讨与门禁校验时读取 |
冲突时遵循三条优先级:材料获取先于来源判断;来源判断先于 Hose 具体探测;审批事实追踪先于坏案例类比。跨阶段请求也要按阶段顺序读取,不能用后置 reference 替代前置 reference。
+5 -2
View File
@@ -72,7 +72,7 @@ seal-use rules version <versionNumber|latest> [--corp <corpId>]
seal-use rules diff <fromVersion> <toVersion> [--code <code>] [--include-unchanged] [--full] [--corp <corpId>]
seal-use rules lint [--file <path>] [--linter <name|path>] [--version <number|latest>] [--code <code>] [--min-score <score>] [--level all|error|warning] [--summary] [--corp <corpId>]
seal-use rules linters [--corp <corpId>]
seal-use rules pull [--version <number|latest>] [--out <file>] [--corp <corpId>]
seal-use rules pull [--official] [--version <number|latest>] [--out <file>] [--corp <corpId>]
seal-use rules push [--file <path>] [--publish] [--version-name <name>] [--dry-run|--yes] [--corp <corpId>]
seal-use rules push status [--file <path>] [--corp <corpId>]
seal-use rules clear [--dry-run|--yes] [--corp <corpId>]
@@ -129,6 +129,8 @@ seal-use report validate <报告.md>
seal-use report render <报告.md> --out <build/报告> [--format <all|html|png|pdf>]
seal-use report export <报告.md> --out <输出目录> [--format <all|html|pdf>]
seal-use report review set [--record-id <ID>] [--sn <SN>] --verdict <v> [--note <text>] [--reviewed-by <who>] [--corp <corpId>]
seal-use report review unreviewed [--limit <n>] [--days <n>] [--all] [--corp <corpId>]
seal-use report review dismiss [--hours <n>] [--corp <corpId>]
seal-use report review list [--corp <corpId>]
seal-use report review import <台账.xlsx|csv> --corp <corpId>
seal-use simulation batch-records <batchId> [--corp <corpId>]
@@ -367,7 +369,8 @@ Approval rule maintenance:
- `seal-use rules diff <fromVersion> <toVersion> [--code <code>] [--include-unchanged] [--full] [--corp <corpId>]` (returns structured changes plus a Git-style `unifiedDiff`; oversized output is truncated only when it exceeds the safety limit)
- `seal-use rules lint [--file <path>] [--linter <name|path>] [--version <number|latest>] [--code <code>] [--min-score <score>] [--level all|error|warning] [--summary] [--corp <corpId>]`
- `seal-use rules linters [--corp <corpId>]` (lists official and custom linters with directory specs: custom in `~/.config/seal-use/linters` and official in `~/.cache/seal-use/linters/official`)
- `seal-use rules pull [--version <number|latest>] [--out <file>] [--corp <corpId>]`
- `seal-use rules pull [--version <number|latest>] [--out <file>] [--corp <corpId>]` saves the current draft or selected published snapshot as local JSON.
- `seal-use rules pull --official [--out <file>] [--corp <corpId>]` calls the SealAI server's CSV export endpoint and saves its returned CSV unchanged (defaults to Downloads). `--official` cannot be combined with `--version`; this endpoint exports the server's current rules and does not expose historical versions.
- `seal-use rules push [--file <path>] [--publish] [--version-name <name>] [--dry-run|--yes] [--corp <corpId>]` incrementally applies the local file: matched IDs are updated, missing local IDs are created, and remote IDs absent from the file are deleted. It does not clear/recreate the whole draft or recode it. Live execution persists a per-step recovery ledger (`status`: `not_started`, `partial`, `completed`, `uncertain`) and hydrates newly created IDs so an interrupted run can be inspected and resumed without duplicating rules.
- `seal-use rules push status [--file <path>] [--corp <corpId>]` (or `--check`) inspects the last push recovery ledger and reconciles remaining diff against the live draft without mutating state.
- `seal-use rules clear [--dry-run|--yes] [--corp <corpId>]`
@@ -238,6 +238,49 @@ seal-use report render <输出目录>/审核报告.md --out <输出目录>/审
seal-use report review import <输出目录>/明细台账.xlsx --corp <corpId>
```
### 模式 C:日常增量少量多次复核(Daily Incremental Triage & Silence Protocol)
**核心契约**:终端用户不敲命令,所有 CLI 指令均由 AI Agent 调度执行。Agent 负责向人类温和征求意见,并严格尊重人类的拒绝意愿,绝不重复打扰。拒绝将机制当作黑盒,Agent 必须透彻理解其背后的数据边界与频控协议。
#### 1. 架构透底:数据资产与时效边界(Agent 上下文认知)
- **本地单机存储**:所有分歧单据与人工复核裁决,均物理持久化在用户本机的 SQLite 数据库(`~/.config/seal-use/state/reviews.sqlite`),**绝不向云端、合思 OpenAPI 或 Seal 平台上传**。
- **时效窗口(近 30 天活跃期)**:CLI 默认只关注最近 30 天内发生的单据(`maxAgeDays = 30`)。超过 30 天的历史单据自动归入离线沉淀归档,日常命令中完全静默,绝不拿半年前的陈年旧账打扰用户(若审计需要,可显式加 `--all` 或 `--days <n>` 检索)。
- **动态频控(5 小时滑动窗口)**:同一个企业距上次提示若不足 5 小时,CLI 绝对静默;满 5 小时后若检测到近期有未整理的分歧,才会在日常企业命令完成后的 `stderr` 信道轻提示一次。
#### 2. 触发信号(stderr 诊断流)
CLI 在执行任意企业相关命令时,若触发条件满足,会在 `stderr` 输出透明指引:
```text
ℹ️ [review-reminder] 检测到企业「华铁大黄蜂」在近 30 天内有 3 笔本地未整理的审核分歧单据(数据仅保存在本机 SQLite,不上传云端)。
👉 Agent 动作指引: 动态频控 5 小时内最多提醒一次。请在完成当前主任务后顺便询问用户是否抽空确认;若用户表示暂不处理,请立即执行: seal-use report review dismiss --corp <corpId> 静音 24 小时,切勿重复打扰。查看待整理详情: seal-use report review unreviewed --corp <corpId>
```
#### 3. Agent 呈报人类的对话规范(轻量顺带,零侵入)
必须在**彻底完成用户当前的主要任务后**,在回复末尾顺便以极简、自然、有安全感的语言征求意见:
> *“本次任务已完成。另外顺便提一句,检测到「华铁大黄蜂」近 30 天有 3 笔单据人工审批和 AI 判定不一致(数据仅保存在你本机电脑),有空的话要顺手确认一下吗?还是改天再说?”*
#### 4. 人类拒绝时的静音规范(24 小时绝对抑制,尊重用户意愿)
若用户表态 *“今天不想审 / 改天吧 / 稍后 / 别提醒我 / 太忙了”*:
- ❌ **Agent 严禁反复复读打扰用户**;
- **Agent 必须立即静默执行静音命令**:
```bash
seal-use report review dismiss --corp <corpId> --hours 24
```
- 系统将该企业静音 24 小时,在此期间无论 5 小时滑动窗口如何,后续命令都绝对闭嘴,Agent 也绝不再主动提起。
#### 5. 人类同意时的极速裁决流程(化整为零)
若用户表示 *“看看是哪几笔”* 或 *“现在弄一下”*:
- Agent 后台拉取未审清单:
```bash
seal-use report review unreviewed --corp <corpId> --limit 5
```
- Agent 将单据关键信息(单号、金额、事由、AI决策理由 vs 人工放行/驳回批注)呈报给用户;
- 用户口头/打字表态(例如:“第1笔AI对,第2笔人工对”);
- Agent 自动调用打标命令回写本地 SQLite 并核销待办:
```bash
seal-use report review set --corp <corpId> --sn <SN> --verdict ai_correct --note "用户确认发票抬头违规"
```
- 少量多次,10 秒钟整理完毕,月末出具商业汇报时所有分歧早已提前就绪!
---
## 六、标准 6 大章节深度剖析
@@ -60,6 +60,19 @@ seal-use rules get 0205 --record-id <recordId> --corp <corpId>
Returns `id`, `code`, `ruleCode`, `runtimeRuleId`, `description`, `scope`, `strictness`, `status`, and version metadata when reading from a published version.
## Pull the Official Server CSV
Use `rules pull --official` when the user wants the CSV generated by the SealAI rules page:
```bash
seal-use rules pull --official --corp <corpId>
seal-use rules pull --official --out <file.csv> --corp <corpId>
```
This calls `GET /api/v1/rules/export/csv` with the configured Seal session. The observed response is a JSON envelope with a `data.csv` string. The command writes that string unchanged to a UTF-8 CSV file; it does not parse rows, rename or reorder columns, normalize line endings, or rebuild the workbook. The response is the official CSV export, not an XLSX file. The endpoint has no observed version parameter, so `--official` cannot be combined with `--version`; use `rules pull --version latest` for the latest published snapshot as JSON.
When `--out` is omitted, the CSV is saved to the user's Downloads directory. CLI stdout remains structured JSON with the output path and byte size.
## Search Rules Compactly
```bash
@@ -0,0 +1,16 @@
# SealAI Browser RUM Replay Endpoint
This reference records the observed browser request to `gc-openway.hosecloud.com` for future diagnostics. It is not an approval or rule-data API.
## Observed request shape
- `POST /v1/write/rum/replay?token=...&to_headless=true&precision=ms`
- `multipart/form-data` with a binary `segment` part and replay metadata such as `start`, `end`, `creation_reason`, `records_count`, `has_full_snapshot`, `index_in_view`, `source`, `sdk_name`, `sdk_version`, `env`, `service`, `app_id`, `session_id`, `view_id`, and `raw_segment_size`.
- The captured request uses `app_id=seal_ai`, `source=browser`, and SDK name `df_web_rum_sdk`.
- `x-datadog-*` request headers and the replay-specific fields indicate a Datadog RUM-compatible browser session replay ingestion/relay endpoint. This is an inference from the request shape; the response and server-side implementation have not been inspected.
## Operational boundary
- The `token` query value is credential material. Never copy it into source code, documentation, CLI output, or logs.
- The uploaded `segment` contains browser replay telemetry. Do not treat it as approval decisions, audit rules, or business documents.
- This endpoint is not part of normal Seal Use CLI operation. Do not embed browser fingerprint emulation or replay credentials in the distributed binary. If future diagnostics need browser replay, keep the adapter separate and use an authorized browser/test session.
+186
View File
@@ -0,0 +1,186 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { runCli } from "../runner.js";
import { saveCorpConfig } from "../../core/config/repository.js";
import {
closeReviewsDb,
recordDivergences
} from "../../domains/seal/reports/pipeline/review-store.js";
import type { CorpConfig } from "../../core/config/types.js";
let tempDir: string;
let originalFetch: typeof globalThis.fetch;
const testCorp: CorpConfig = {
id: "corp-triage-test",
name: "测试分歧企业",
environment: "production",
seal: {
url: "https://triage.sealai.cc",
tenantSlug: "triage",
endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" }
},
source: {
type: "seal",
token: "dummy-token",
sealUrl: "https://triage.sealai.cc",
expiresIn: 3600,
staffId: "u-triage",
corpId: "corp-triage-test",
tenantId: "t-triage",
tenantSlug: "triage",
provider: "seal"
},
auth: { refreshTtl: 300 }
};
describe("report review CLI: 面向 Agent 的分歧待办查询与静音抑制", () => {
beforeEach(() => {
tempDir = mkdtempSync(join(tmpdir(), "seal-report-review-cli-test-"));
process.env.SEAL_USE_ENTERPRISES_DIR = join(tempDir, "enterprises");
process.env.SEAL_USE_REVIEWS_STORE = join(tempDir, "reviews.sqlite");
process.env.SEAL_USE_REVIEWS_DIR = join(tempDir, "reviews");
saveCorpConfig(testCorp, { overwrite: true });
originalFetch = globalThis.fetch;
globalThis.fetch = (async () => {
return new Response(JSON.stringify({ rules: [], hasPendingDeletes: false }), {
status: 200,
headers: { "content-type": "application/json" }
});
}) as unknown as typeof globalThis.fetch;
});
afterEach(() => {
globalThis.fetch = originalFetch;
closeReviewsDb();
delete process.env.SEAL_USE_ENTERPRISES_DIR;
delete process.env.SEAL_USE_REVIEWS_STORE;
delete process.env.SEAL_USE_REVIEWS_DIR;
rmSync(tempDir, { recursive: true, force: true });
});
test("report review unreviewed 列出待整理分歧单据并附带 Agent 指引", async () => {
recordDivergences(testCorp.id, [
{
corpId: testCorp.id,
recordId: "run-div-1",
sn: "SN-DIV-001",
docTitle: "差旅申请单",
amount: "¥800",
aiDecision: "驳回",
manualDecision: "通过",
divergenceType: "AI驳回_人工通过",
discoveredAt: Date.now()
}
]);
const result = await runCli([
"report",
"review",
"unreviewed",
"--corp",
testCorp.id
]);
expect(result.exitCode).toBe(0);
const parsed = JSON.parse(result.stdout);
expect(parsed.corpId).toBe(testCorp.id);
expect(parsed.count).toBe(1);
expect(parsed.divergences[0].sn).toBe("SN-DIV-001");
expect(parsed.guidance).toContain("Agent 上下文说明");
expect(parsed.guidance).toContain("5 小时滑动窗口");
});
test("report review dismiss 成功静音并在期限内抑制提示", async () => {
recordDivergences(testCorp.id, [
{
corpId: testCorp.id,
recordId: "run-div-1",
sn: "SN-DIV-001",
discoveredAt: Date.now()
}
]);
// 用户表示今天不想看,Agent 调度 dismiss 24小时
const dismissRes = await runCli([
"report",
"review",
"dismiss",
"--hours",
"24",
"--corp",
testCorp.id
]);
expect(dismissRes.exitCode).toBe(0);
const parsedDismiss = JSON.parse(dismissRes.stdout);
expect(parsedDismiss.dismissed).toBe(true);
expect(parsedDismiss.message).toContain("已为企业「测试分歧企业」静音分歧提醒 24 小时");
});
test("stderr 注入:在日常命令完成时提示 Agent,dismiss 后不再提示", async () => {
recordDivergences(testCorp.id, [
{
corpId: testCorp.id,
recordId: "run-div-1",
sn: "SN-DIV-001",
discoveredAt: Date.now()
}
]);
// 运行一个常规的企业级数据命令(例如 rules count)
const resBefore = await runCli([
"rules",
"count",
"--corp",
testCorp.id
]);
// stderr 应注入面向 Agent 的提醒
expect(resBefore.stderr).toContain("ℹ️ [review-reminder]");
expect(resBefore.stderr).toContain("Agent 动作指引");
// Agent 调用 dismiss 静音
await runCli([
"report",
"review",
"dismiss",
"--corp",
testCorp.id
]);
// 再次运行命令,stderr 不再打扰
const resAfter = await runCli([
"rules",
"count",
"--corp",
testCorp.id
]);
expect(resAfter.stderr).not.toContain("ℹ️ [review-reminder]");
});
test("超过 30 天的历史旧单不触发日常命令 stderr 提醒", async () => {
const oldTime = Date.now() - 60 * 24 * 3600 * 1000;
recordDivergences(testCorp.id, [
{
corpId: testCorp.id,
recordId: "run-old-1",
sn: "SN-OLD-001",
createdAt: oldTime,
discoveredAt: oldTime
}
]);
const res = await runCli([
"rules",
"count",
"--corp",
testCorp.id
]);
expect(res.stderr).not.toContain("ℹ️ [review-reminder]");
});
});
+54 -8
View File
@@ -16,6 +16,9 @@ import {
loadReviews,
reviewFilePath,
writeReview,
countUnreviewedDivergences,
listUnreviewedDivergences,
dismissDivergencePrompt,
type MonthlyReportResult,
buildReportLedgerCsv,
buildReportLedgerXlsx,
@@ -29,13 +32,19 @@ import type { ParsedArgs } from "../types.js";
export async function handleLocalReportCommand(action: string | undefined, args: ParsedArgs) {
if (Boolean(args.options.ledger) || action === "review") {
const corpId = stringOption(args.options.corp) ?? stringOption(args.options.corpId) ?? "local-ledger";
const corp = {
corpId,
id: corpId,
name: corpId,
corpName: corpId,
source: { source: "seal", sealUrl: "" }
} as unknown as CorpConfig;
let corp: CorpConfig;
try {
const { selectCorp } = await import("../helpers.js");
corp = selectCorp(corpId);
} catch {
corp = {
corpId,
id: corpId,
name: corpId,
corpName: corpId,
source: { source: "seal", sealUrl: "" }
} as unknown as CorpConfig;
}
await handleReportCommand(action, {} as any, corp, args);
return;
}
@@ -282,6 +291,43 @@ export async function handleReportCommand(
if (action === "review") {
const sub = args.command[2]; // set | list | import
if (sub === "unreviewed" || sub === "pending" || sub === "triage") {
const limit = numberOption(args.options.limit) ?? 20;
const all = booleanOption(args.options.all);
const days = all ? 0 : (numberOption(args.options.days) ?? 30);
const items = listUnreviewedDivergences(corp.id, limit, days);
printJson({
corpId: corp.id,
corpName: corp.name,
window: {
recencyDays: days > 0 ? days : "all",
promptThrottleHours: 5,
storage: "~/.config/seal-use/state/reviews.sqlite"
},
count: items.length,
totalPending: countUnreviewedDivergences(corp.id, days),
divergences: items,
guidance:
"Agent 上下文说明:\n" +
"1. 数据来源:上述分歧来自本地 SQLite (~/.config/seal-use/state/reviews.sqlite),由报表或审批流发现 AI 与人工结论相反,仅保存在用户本机,不上传云端。\n" +
"2. 频控规则:CLI 默认只关注近 30 天内单据(排除陈年旧账),且每 5 小时滑动窗口最多提醒一次。\n" +
"3. 交互流程:请在完成主任务后以简短摘要向用户征询;用户确认后执行 'seal-use report review set --corp <corpId> --sn <SN> --verdict <ai_correct|manual_correct|both_correct|both_wrong|unclear>' 回写;用户表示暂不处理时,立即执行 'seal-use report review dismiss --corp <corpId> --hours 24' 静音 24 小时,切勿重复打扰。"
}, outputOptions(args.options));
return;
}
if (sub === "dismiss") {
const hours = numberOption(args.options.hours) ?? 24;
const until = dismissDivergencePrompt(corp.id, hours);
printJson({
corpId: corp.id,
dismissed: true,
dismissedUntil: new Date(until).toISOString(),
message: `已为企业「${corp.name}」静音分歧提醒 ${hours} 小时。在此期间不会重复向用户提示。`
}, outputOptions(args.options));
return;
}
if (sub === "list") {
const scope = stringOption(args.options.month) ?? stringOption(args.options.scope);
const reviews = loadReviews(corp.id, scope);
@@ -341,7 +387,7 @@ export async function handleReportCommand(
return;
}
throw usageError(`Unknown report review subcommand: ${sub ?? ""}. Use 'set', 'list', or 'import'.`);
throw usageError(`Unknown report review subcommand: ${sub ?? ""}. Use 'set', 'list', 'unreviewed', 'dismiss', or 'import'.`);
}
throw usageError(`Unknown report command: ${action ?? ""}. Run 'seal-use help report' for available commands.`);
+13
View File
@@ -327,6 +327,19 @@ export async function handleRulesCommand(
if (action === "pull") {
const version = resolveVersionOption(args, maybeName);
const out = stringOption(args.options.out) ?? stringOption(args.options.file) ?? stringOption(args.options.f);
if (booleanOption(args.options.official) === true) {
if (version) {
throw usageError("rules pull --official uses SealAI's official current-rules CSV export and cannot be combined with --version.");
}
await runCapability(
"sealApprovalRulesExportCsv",
client!,
corp,
{ out },
outputOptions(args.options)
);
return;
}
await runCapability(
"sealApprovalRulesPull",
client!,
+18 -3
View File
@@ -349,8 +349,23 @@ describe("update installation modes", () => {
expect(SYSTEM_BINARY_PATH).toBe("/usr/local/bin/seal-use");
});
test("cleanStaleBinaries ignores activePath and returns list of cleaned files", () => {
const cleaned = cleanStaleBinaries(SYSTEM_BINARY_PATH);
expect(Array.isArray(cleaned)).toBe(true);
test("cleanStaleBinaries ignores activePath and returns list of cleaned files in isolated sandbox", () => {
const tempDir = mkdtempSync(join(tmpdir(), "seal-use-clean-test-"));
try {
const fakeActive = join(tempDir, "active-bin");
const fakeStale = join(tempDir, "stale-bin");
const fakeUntouched = join(tempDir, "untouched-bin");
writeFileSync(fakeActive, "active");
writeFileSync(fakeStale, "stale");
writeFileSync(fakeUntouched, "untouched");
const cleaned = cleanStaleBinaries(fakeActive, [fakeActive, fakeStale]);
expect(cleaned).toEqual([fakeStale]);
expect(existsSync(fakeActive)).toBe(true);
expect(existsSync(fakeStale)).toBe(false);
expect(existsSync(fakeUntouched)).toBe(true);
} finally {
rmSync(tempDir, { recursive: true, force: true });
}
});
});
+8 -6
View File
@@ -39,7 +39,7 @@ export function isPathWritable(targetPath: string): boolean {
}
}
export function cleanStaleBinaries(activePath: string): string[] {
export function cleanStaleBinaries(activePath: string, candidateOverrides?: string[]): string[] {
const cleaned: string[] = [];
const home = homedir();
const userBinary = getUserBinaryPath();
@@ -49,11 +49,13 @@ export function cleanStaleBinaries(activePath: string): string[] {
const homebrewBinary = "/opt/homebrew/bin/seal-use";
const homebrewAlias = "/opt/homebrew/bin/seal-home";
const candidates = [homebrewBinary, homebrewAlias];
if (activePath === systemBinary) {
candidates.push(userBinary, userAlias);
} else if (activePath === userBinary) {
candidates.push(systemBinary, systemAlias);
const candidates = candidateOverrides ? [...candidateOverrides] : [homebrewBinary, homebrewAlias];
if (!candidateOverrides) {
if (activePath === systemBinary) {
candidates.push(userBinary, userAlias);
} else if (activePath === userBinary) {
candidates.push(systemBinary, systemAlias);
}
}
for (const candidate of candidates) {
+30 -3
View File
@@ -340,8 +340,13 @@ export const HELP_REGISTRY: AreaHelp[] = [
},
{
name: "pull",
summary: "Export rules to local JSON file",
usage: ["seal-use rules pull [--version <number|latest>] [--out <file>] [--corp <corpId>]"]
summary: "Pull rules as local JSON, or use --official for the server-generated CSV",
usage: ["seal-use rules pull [--official] [--version <number|latest>] [--out <file>] [--corp <corpId>]"],
options: [
{ flag: "--official", description: "Call SealAI's official CSV export endpoint and save its returned CSV unchanged; cannot be combined with --version" },
{ flag: "--version <number|latest>", description: "Pull a published version as JSON; unavailable with --official" },
{ flag: "--out <file>", description: "Output path; defaults to ./rules.local.json for JSON or Downloads for official CSV" }
]
},
{
name: "push",
@@ -766,7 +771,29 @@ export const HELP_REGISTRY: AreaHelp[] = [
{ flag: "--note <text>", description: "Optional adjudication note" },
{ flag: "--reviewed-by <who>", description: "Optional reviewer name for the audit trail" }
],
description: "Append-only local JSONL per tenant (~/.config/seal-use/state/reviews/). Supports exact recordId target or SN. Typically adjudicates diverged blocks or overrides specific agreed runs."
description: "Local SQLite store with companion JSONL (~/.config/seal-use/state/reviews.sqlite). Supports exact recordId target or SN. Typically adjudicates diverged blocks or overrides specific agreed runs."
},
{
name: "review unreviewed",
summary: "List unreviewed human-AI divergence records for incremental triaging",
usage: ["seal-use report review unreviewed [--limit <n>] [--days <n>] [--all] [--corp <corpId>]"],
options: [
{ flag: "--limit <n>", description: "Max unreviewed items to return (default 20)" },
{ flag: "--days <n>", description: "Only return records created within recent days (default 30)" },
{ flag: "--all", description: "Include all historical unreviewed records regardless of age" },
{ flag: "--corp <corpId>", description: "Target enterprise corpId" }
],
description: "Returns unadjudicated diverged records from local SQLite (~/.config/seal-use/state/reviews.sqlite). CLI throttles reminder notifications on a 5-hour sliding window and filters to recent 30 days to avoid ancient debt. Use this command to fetch items, present a natural-language summary to the user, and record verdicts with 'report review set'."
},
{
name: "review dismiss",
summary: "Suppress divergence reminders for a tenant when the user declines reviewing",
usage: ["seal-use report review dismiss [--hours <n>] [--corp <corpId>]"],
options: [
{ flag: "--hours <n>", description: "Hours to suppress reminders (default 24)" },
{ flag: "--corp <corpId>", description: "Target enterprise corpId" }
],
description: "Mutes CLI divergence prompts for the enterprise for N hours (default 24h) when the user declines reviewing. Agents must call this immediately when the user says 'not now' or 'later' to ensure zero repeated disruption."
},
{
name: "review list",
+4
View File
@@ -27,6 +27,10 @@ describe("parseArgs flag handling", () => {
expect(parseArgs(["corps", "list", "--all"]).options.all).toBe(true);
});
test("rules pull official is parsed as a boolean flag", () => {
expect(parseArgs(["rules", "pull", "--official"]).options.official).toBe(true);
});
test("value flags consume exactly one token", () => {
const parsed = parseArgs(["approval-runs", "list", "--limit", "25", "--status", "completed"]);
+3 -3
View File
@@ -31,7 +31,7 @@ export const BOOLEAN_FLAGS = new Set([
"exclude-deleted", "extract", "extract-expenses", "extractExpenses", "fail-on-flips", "flow", "force", "full", "glossary", "has-input", "has-output", "help",
"has-extra-risk", "hasExtraRisk", "hose", "hose-outbound", "hose-sso", "hoseOutbound", "hoseSso", "include-deleted", "include-io-preview", "include-simulation", "include-unchanged",
"include-bridge", "includeBridge", "includeSimulation", "includeUnchanged", "local", "no-attachments", "no-flow", "no-glossary",
"no-wait", "noWait", "outbound", "overwrite", "plain", "publish", "quiet",
"no-wait", "noWait", "official", "outbound", "overwrite", "plain", "publish", "quiet",
"r", "raw-json", "rawJson", "recode", "refresh", "refresh-if-missing", "reveal", "rotate-secret", "rotateSecret",
"save", "silent", "silent-save", "simulation", "skip-expense-extraction", "skip-extract", "skip-invoice-generation",
"skipExpenseExtraction", "skipExtract", "skipInvoiceGeneration", "snippet-only", "snippetOnly", "sso", "strict",
@@ -47,7 +47,7 @@ export const VALUE_FLAGS = new Set([
"access-token", "accessToken", "action", "add-approver-ids", "addApproverIds", "ai", "ai-accuracy", "aiAccuracy", "app-key", "app-security", "appKey", "appSecurity",
"base-url", "batch", "batch-id", "batchId", "both", "both-accurate", "bothAccurate", "business-codes", "businessCodes",
"channel", "chrome", "code", "comment", "concurrency", "confirm-code", "confirmCode", "content", "content-file", "content-hints", "content-type", "contentFile",
"content-format", "contentFormat", "contentType", "context-chars", "context-lines", "contextLines", "corp", "corp-id", "corpId", "corporation-id", "corporationId", "date",
"content-format", "contentFormat", "contentType", "context-chars", "context-lines", "contextLines", "corp", "corp-id", "corpId", "corporation-id", "corporationId", "date", "days",
"dedupe-by", "dedupeBy", "default", "departmentId", "dept", "desc",
"description", "description-file", "descriptionFile", "dir", "doc-id-prefix", "doc-id-suffix",
"docIdPrefix", "docIdSuffix", "document-id", "document-sn", "document-sns", "document-type",
@@ -55,7 +55,7 @@ export const VALUE_FLAGS = new Set([
"end", "end-date", "end-time", "endDate", "endTime", "env",
"environment", "expire", "expires-in", "expiresIn", "fields", "file", "file-id", "file-name", "flow-concurrency",
"flow-id", "flow-ids", "flow-status-list", "flowId", "flowIds", "flowStatusList", "format", "from",
"from-link", "host", "human", "human-accuracy", "humanAccuracy", "human-result", "humanResult", "id", "input", "integration",
"from-link", "host", "hours", "human", "human-accuracy", "humanAccuracy", "human-result", "humanResult", "id", "input", "integration",
"json", "json-path", "key-id", "keyId", "keyword", "ledger", "level", "limit",
"lines", "link", "linter", "manual-approval-status", "manual-status", "manualApprovalStatus", "manualStatus",
"max-chars", "max-preview-chars", "maxChars", "maxResults", "max-results", "message-id", "messageId", "metadata", "metadata-key", "min-score", "minScore", "mode",
+19
View File
@@ -349,9 +349,27 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
const corp = (await import("./helpers.js")).selectCorp(stringOption(args.options.corp));
const maybePromptDivergences = async () => {
if (area === "report" && action === "review") return;
try {
const { countUnreviewedDivergences, shouldPromptDivergence } = await import(
"../domains/seal/reports/pipeline/review-store.js"
);
const count = countUnreviewedDivergences(corp.id, 30);
if (count > 0 && shouldPromptDivergence(corp.id)) {
console.error(
`ℹ️ [review-reminder] 检测到企业「${corp.name}」在近 30 天内有 ${count} 笔本地未整理的审核分歧单据(数据仅保存在本机 SQLite,不上传云端)。\n👉 Agent 动作指引: 动态频控 5 小时内最多提醒一次。请在完成当前主任务后顺便询问用户是否抽空确认;若用户表示暂不处理,请立即执行: seal-use report review dismiss --corp ${corp.id} 静音 24 小时,切勿重复打扰。查看待整理详情: seal-use report review unreviewed --corp ${corp.id}`
);
}
} catch {
// 容错降级,不阻断主流程
}
};
const corpCommand = CORP_COMMANDS[area];
if (corpCommand) {
await corpCommand(args, corp);
await maybePromptDivergences();
return;
}
@@ -359,6 +377,7 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
if (clientCommand) {
const client = await (await import("../core/http/factory.js")).createSealClient(corp);
await clientCommand(args, corp, client);
await maybePromptDivergences();
return;
}
+44
View File
@@ -17,6 +17,7 @@ export interface SealDelegateSealSession {
sealUrl: string;
token: string;
expiresIn: number;
sessionCookie?: string;
user: Record<string, unknown>;
tenant: Record<string, unknown>;
}
@@ -199,11 +200,54 @@ export async function exchangeSealDelegateLink(
sealUrl,
token: bearerToken,
expiresIn,
sessionCookie: sessionCookie || undefined,
user,
tenant
};
}
/**
* 调用 SealAI 服务端为当前租户创建新的协助授权链接(最长支持 168 小时 / 7 天)
*/
export async function createSealDelegationLink(
sealUrl: string,
options?: {
cookie?: string;
token?: string;
expiresInHours?: number;
note?: string;
customHeaders?: Record<string, string>;
}
): Promise<{ link: string; token: string; expiresInHours: number }> {
const expiresInHours = options?.expiresInHours ?? 168;
const note = options?.note ?? "权限续期";
const headers: Record<string, string> = {
...options?.customHeaders
};
if (options?.cookie) {
headers.Cookie = options.cookie;
}
const client = createSealClientForUrl(sealUrl, options?.token, headers);
const resp = await client
.post("api/v1/delegation/create", {
json: { expiresInHours, note }
})
.json<{
data?: { link?: string; token?: string };
link?: string;
token?: string;
}>();
const link = resp.data?.link ?? resp.link;
const token = resp.data?.token ?? resp.token;
if (!link || !token) {
throw new Error("Seal create delegation did not return a valid link/token");
}
return { link, token, expiresInHours };
}
/* ------------------------------------------------------------------ *
* Link-type scoring (classification by score)
* ------------------------------------------------------------------ */
+318
View File
@@ -0,0 +1,318 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { CorpConfig } from "../config/types.js";
import {
clearSealToken,
getSealSessionForCorp,
recoverSealSessionForCorp,
renewNativeSealSession
} from "./seal.js";
import {
getSealDelegateAuthCache,
getSealSession,
setSealDelegateAuthCache
} from "./token-store.js";
const originalFetch = globalThis.fetch;
let tempDir: string;
let storePath: string;
const fixtureCorp: CorpConfig = {
id: "test-delegate-corp",
name: "测试委托租户",
environment: "production",
seal: {
url: "https://mytenant.sealai.cc",
tenantSlug: "mytenant",
endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" }
},
source: {
type: "seal",
token: "initial-static-token",
sealUrl: "https://mytenant.sealai.cc",
expiresIn: 3600,
expiresAt: new Date(Date.now() + 3600 * 1000).toISOString(),
staffId: "u-123",
corpId: "test-delegate-corp",
tenantId: "t-456",
tenantSlug: "mytenant",
tenantName: "My Tenant",
provider: "seal"
},
auth: { refreshTtl: 300 }
};
describe("seal-renew: 原生 Seal 协助授权长效续期与会话池救险", () => {
beforeEach(() => {
tempDir = mkdtempSync(join(tmpdir(), "seal-renew-test-"));
storePath = join(tempDir, "tokens.json");
process.env.SEAL_USE_TOKEN_STORE = storePath;
clearSealToken(fixtureCorp.id);
});
afterEach(() => {
globalThis.fetch = originalFetch;
clearSealToken(fixtureCorp.id);
delete process.env.SEAL_USE_TOKEN_STORE;
rmSync(tempDir, { recursive: true, force: true });
});
test("无可用 Cookie 时安全返回 undefined,平滑回退到静态 token", async () => {
const renewed = await renewNativeSealSession(fixtureCorp);
expect(renewed).toBeUndefined();
const session = await getSealSessionForCorp(fixtureCorp);
expect(session.token).toBe("initial-static-token");
});
test("主 Cookie 有效时成功自动续期换发新 token,并轮转归档历史 Cookie", async () => {
setSealDelegateAuthCache(fixtureCorp.id, {
cookie: "__Secure-x-seal.session_token=old-cookie-token",
backupCookies: []
});
let delegationCreateCalledWithCookie = "";
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const url = new URL(
typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url
);
const headers = input instanceof Request ? input.headers : new Headers(init?.headers);
if (url.pathname === "/api/v1/delegation/create") {
delegationCreateCalledWithCookie = headers.get("cookie") || "";
return new Response(
JSON.stringify({
data: {
link: "https://mytenant.sealai.cc/delegate?token=minted-delegation-token",
token: "minted-delegation-token"
}
}),
{ headers: { "Content-Type": "application/json" } }
);
}
if (url.pathname === "/api/v1/delegation/consume") {
return new Response(
JSON.stringify({
data: {
userId: "u-123",
userName: "Alice",
tenantId: "t-456",
tenantName: "My Tenant",
delegationId: "del-new"
}
}),
{
headers: {
"Content-Type": "application/json",
"Set-Cookie":
"__Secure-x-seal.session_token=fresh-cookie-token.sig; Path=/; HttpOnly; Secure"
}
}
);
}
if (url.pathname === "/api/auth/get-session") {
return new Response(
JSON.stringify({
user: { id: "u-123", name: "Alice" },
session: {
token: "brand-new-bearer-token",
expiresAt: new Date(Date.now() + 168 * 3600 * 1000).toISOString()
}
}),
{ headers: { "Content-Type": "application/json" } }
);
}
if (url.pathname === "/api/v1/auth/me") {
return new Response(
JSON.stringify({
data: {
user: { id: "u-123", name: "Alice" },
tenant: { id: "t-456", name: "My Tenant", tenantSlug: "mytenant" }
}
}),
{ headers: { "Content-Type": "application/json" } }
);
}
return new Response("Not found", { status: 404 });
}) as typeof fetch;
const renewed = await renewNativeSealSession(fixtureCorp);
expect(renewed).toBeDefined();
expect(renewed!.token).toBe("brand-new-bearer-token");
expect(delegationCreateCalledWithCookie).toBe(
"__Secure-x-seal.session_token=old-cookie-token"
);
// 检查 tokens.json 中更新状态
const delegateCache = getSealDelegateAuthCache(fixtureCorp.id);
expect(delegateCache.cookie).toBe("__Secure-x-seal.session_token=fresh-cookie-token.sig");
expect(delegateCache.backupCookies).toEqual(["__Secure-x-seal.session_token=old-cookie-token"]);
// 再次读取 session 命中新缓存
const session = await getSealSessionForCorp(fixtureCorp);
expect(session.token).toBe("brand-new-bearer-token");
});
test("主 Cookie 失效时,依次由 backupCookies 兜底救险成功(断电超期场景)", async () => {
// 模拟主 Cookie 已在服务端注销失效,但历史 backupCookies 中包含一份 30 天未过期的长效会话
setSealDelegateAuthCache(fixtureCorp.id, {
cookie: "expired-cookie",
backupCookies: ["valid-backup-cookie"]
});
const attemptedCookies: string[] = [];
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const url = new URL(
typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url
);
const headers = input instanceof Request ? input.headers : new Headers(init?.headers);
if (url.pathname === "/api/v1/delegation/create") {
const cookie = headers.get("cookie") || "";
attemptedCookies.push(cookie);
if (cookie === "expired-cookie") {
return new Response(JSON.stringify({ error: { message: "Session expired" } }), {
status: 401,
headers: { "Content-Type": "application/json" }
});
}
return new Response(
JSON.stringify({
data: {
link: "https://mytenant.sealai.cc/delegate?token=rescued-delegation-token",
token: "rescued-delegation-token"
}
}),
{ headers: { "Content-Type": "application/json" } }
);
}
if (url.pathname === "/api/v1/delegation/consume") {
return new Response(
JSON.stringify({
data: {
userId: "u-123",
userName: "Alice",
tenantId: "t-456",
tenantName: "My Tenant"
}
}),
{
headers: {
"Content-Type": "application/json",
"Set-Cookie": "__Secure-x-seal.session_token=rescued-cookie.sig; Path=/; HttpOnly"
}
}
);
}
if (url.pathname === "/api/auth/get-session") {
return new Response(
JSON.stringify({
session: {
token: "rescued-bearer-token",
expiresAt: new Date(Date.now() + 168 * 3600 * 1000).toISOString()
}
}),
{ headers: { "Content-Type": "application/json" } }
);
}
if (url.pathname === "/api/v1/auth/me") {
return new Response(
JSON.stringify({
data: {
user: { id: "u-123", name: "Alice" },
tenant: { id: "t-456", name: "My Tenant", tenantSlug: "mytenant" }
}
}),
{ headers: { "Content-Type": "application/json" } }
);
}
return new Response("Not found", { status: 404 });
}) as typeof fetch;
const renewed = await renewNativeSealSession(fixtureCorp);
expect(renewed).toBeDefined();
expect(renewed!.token).toBe("rescued-bearer-token");
expect(attemptedCookies).toEqual(["expired-cookie", "valid-backup-cookie"]);
const delegateCache = getSealDelegateAuthCache(fixtureCorp.id);
expect(delegateCache.cookie).toBe("__Secure-x-seal.session_token=rescued-cookie.sig");
expect(delegateCache.backupCookies).toContain("valid-backup-cookie");
});
test("recoverSealSessionForCorp 在收到 401 时自动触发自愈", async () => {
setSealDelegateAuthCache(fixtureCorp.id, {
cookie: "valid-cookie",
backupCookies: []
});
globalThis.fetch = (async (input: RequestInfo | URL) => {
const url = new URL(
typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url
);
if (url.pathname === "/api/v1/delegation/create") {
return new Response(
JSON.stringify({
data: {
link: "https://mytenant.sealai.cc/delegate?token=recovered-delegation-token",
token: "recovered-delegation-token"
}
}),
{ headers: { "Content-Type": "application/json" } }
);
}
if (url.pathname === "/api/v1/delegation/consume") {
return new Response(
JSON.stringify({
data: { userId: "u-123", userName: "Alice", tenantId: "t-456", tenantName: "My Tenant" }
}),
{
headers: {
"Content-Type": "application/json",
"Set-Cookie": "__Secure-x-seal.session_token=recovered-cookie.sig"
}
}
);
}
if (url.pathname === "/api/auth/get-session") {
return new Response(
JSON.stringify({
session: {
token: "recovered-bearer-token",
expiresAt: new Date(Date.now() + 168 * 3600 * 1000).toISOString()
}
}),
{ headers: { "Content-Type": "application/json" } }
);
}
if (url.pathname === "/api/v1/auth/me") {
return new Response(
JSON.stringify({
data: {
user: { id: "u-123", name: "Alice" },
tenant: { id: "t-456", name: "My Tenant", tenantSlug: "mytenant" }
}
}),
{ headers: { "Content-Type": "application/json" } }
);
}
return new Response("Not found", { status: 404 });
}) as typeof fetch;
// 假设当前正在使用 stale-token 遭遇 401
const recovered = await recoverSealSessionForCorp(fixtureCorp, "initial-static-token");
expect(recovered.token).toBe("recovered-bearer-token");
const sessionInStore = getSealSession(fixtureCorp.id);
expect(sessionInStore?.token).toBe("recovered-bearer-token");
});
});
+106 -2
View File
@@ -1,8 +1,22 @@
import { CorpConfig } from "../config/types.js";
import { getNativeSealSession } from "./native.js";
import { getHoseSealSession } from "./hose.js";
import { clearSealSession, getSealSession, setSealSession } from "./token-store.js";
import {
clearSealSession,
getSealDelegateAuthCache,
getSealSession,
setSealDelegateAuthCache,
setSealSession
} from "./token-store.js";
import { SealEnterpriseConfig, SealSession } from "./types.js";
import {
attemptCreateDelegationWithFallback,
resolveCandidateCookies,
rotateBackupCookies
} from "./session-fallback.js";
import { createSealDelegationLink, exchangeSealDelegateLink } from "./delegate.js";
import { saveCorpConfig } from "../config/repository.js";
import { formatBeijingIso } from "../config/timestamps.js";
const memoryCache = new Map<string, SealSession>();
const pendingSessions = new Map<string, Promise<SealSession>>();
@@ -11,12 +25,102 @@ function isExpired(session: SealSession, refreshTtl: number): boolean {
return Date.now() >= session.expiresAt - refreshTtl * 1000;
}
/**
* 为原生 Seal 租户执行协助授权续期换发。
* 优先使用主 Cookie,遇到失效或断电超期时依次由 backupCookies 兜底救险。
*/
export async function renewNativeSealSession(corp: CorpConfig): Promise<SealSession | undefined> {
const source = corp.source;
if (source.type !== "seal") return undefined;
const authCache = getSealDelegateAuthCache(corp.id);
const candidateCookies = resolveCandidateCookies(authCache);
if (candidateCookies.length === 0) return undefined;
const sealUrl = corp.seal.url ?? source.sealUrl;
const delegation = await attemptCreateDelegationWithFallback(
candidateCookies,
async (candCookie) => {
return createSealDelegationLink(sealUrl, {
cookie: candCookie,
token: source.token,
expiresInHours: 168,
note: "权限续期"
});
}
);
const exchanged = await exchangeSealDelegateLink({
sealUrl,
delegateToken: delegation.token
});
const newCookie = exchanged.sessionCookie;
const backupCookies = rotateBackupCookies(authCache, newCookie, authCache.backupCookies, 5);
setSealDelegateAuthCache(corp.id, {
cookie: newCookie ?? authCache.cookie,
backupCookies,
updatedAt: Date.now()
});
const nextSession: SealSession = {
token: exchanged.token,
expiresAt: Date.now() + exchanged.expiresIn * 1000,
enterprise: {
provider: source.provider ?? "seal",
corpId: source.corpId ?? corp.id,
staffId: source.staffId,
sealUrl,
tenantId: source.tenantId ?? (exchanged.tenant.id as string | undefined),
tenantSlug:
corp.seal.tenantSlug ??
source.tenantSlug ??
(exchanged.tenant.tenantSlug as string | undefined),
tenantName: source.tenantName ?? (exchanged.tenant.name as string | undefined),
raw: {
sourceType: "seal"
}
}
};
// 尝试静默同步更新静态租户配置中的 token 与 expiresAt,避免不读缓存时使用陈旧 token
try {
const updatedCorp: CorpConfig = {
...corp,
source: {
...source,
token: exchanged.token,
expiresIn: exchanged.expiresIn,
expiresAt: formatBeijingIso(nextSession.expiresAt)
}
};
saveCorpConfig(updatedCorp, { overwrite: true });
} catch {
// 忽略无法写回配置文件的异常(如沙箱环境或只读配置)
}
return nextSession;
}
async function refreshSealSession(corp: CorpConfig): Promise<SealSession> {
switch (corp.source.type) {
case "hose":
return getHoseSealSession(corp);
case "seal":
case "seal": {
const authCache = getSealDelegateAuthCache(corp.id);
const candidates = resolveCandidateCookies(authCache);
if (candidates.length > 0) {
try {
const renewed = await renewNativeSealSession(corp);
if (renewed) return renewed;
} catch {
// 续签失败时平滑降级到原有静态凭证
}
}
return getNativeSealSession(corp);
}
}
}
+95
View File
@@ -0,0 +1,95 @@
import { describe, expect, test } from "bun:test";
import {
attemptCreateDelegationWithFallback,
resolveCandidateCookies,
rotateBackupCookies
} from "./session-fallback.js";
describe("session-fallback", () => {
test("rotateBackupCookies: 初始无历史 Cookie 时返回空备份", () => {
const result = rotateBackupCookies(undefined, "cookie-1");
expect(result).toEqual([]);
});
test("rotateBackupCookies: 更新 Cookie 时自动归档上一份会话且排除当前 Cookie", () => {
const existing = { cookie: "cookie-1", backupCookies: [] };
const result = rotateBackupCookies(existing, "cookie-2");
expect(result).toEqual(["cookie-1"]);
});
test("rotateBackupCookies: 连续轮换自动去重并严格限制上限为 5 份", () => {
let existing: { cookie?: string; backupCookies?: string[] } = {
cookie: "cookie-1",
backupCookies: []
};
for (let i = 2; i <= 8; i++) {
const newCookie = `cookie-${i}`;
const backups = rotateBackupCookies(existing, newCookie);
existing = { cookie: newCookie, backupCookies: backups };
}
expect(existing.cookie).toBe("cookie-8");
expect(existing.backupCookies?.length).toBe(5);
expect(existing.backupCookies).toEqual([
"cookie-7",
"cookie-6",
"cookie-5",
"cookie-4",
"cookie-3"
]);
});
test("resolveCandidateCookies: 优先返回当前主 Cookie 并依次排列历史长效备份", () => {
expect(resolveCandidateCookies(undefined)).toEqual([]);
expect(resolveCandidateCookies({})).toEqual([]);
const result = resolveCandidateCookies({
cookie: "main-cookie",
backupCookies: ["backup-1", "backup-2", "main-cookie"]
});
expect(result).toEqual(["main-cookie", "backup-1", "backup-2"]);
});
test("attemptCreateDelegationWithFallback: 主 Cookie 成功时直接返回结果", async () => {
const tried: (string | undefined)[] = [];
const res = await attemptCreateDelegationWithFallback(
["cookie-primary", "cookie-backup-1"],
async (cookie) => {
tried.push(cookie);
return { link: "https://seal.cc/delegate?token=new", token: "new-token" };
}
);
expect(res.token).toBe("new-token");
expect(tried).toEqual(["cookie-primary"]);
});
test("attemptCreateDelegationWithFallback: 主 Cookie 失败时依次由备份 Cookie 兜底救险", async () => {
const tried: (string | undefined)[] = [];
const res = await attemptCreateDelegationWithFallback(
["expired-cookie", "valid-backup-cookie"],
async (cookie) => {
tried.push(cookie);
if (cookie === "expired-cookie") {
throw new Error("401 Unauthorized");
}
return { link: "https://seal.cc/delegate?token=rescued", token: "rescued-token" };
}
);
expect(res.token).toBe("rescued-token");
expect(tried).toEqual(["expired-cookie", "valid-backup-cookie"]);
});
test("attemptCreateDelegationWithFallback: 全部候选失败时抛出最后的错误", async () => {
await expect(
attemptCreateDelegationWithFallback(
["bad-1", "bad-2"],
async (cookie) => {
throw new Error(`Failed with ${cookie}`);
}
)
).rejects.toThrow("Failed with bad-2");
});
});
+58
View File
@@ -0,0 +1,58 @@
/**
* 维护会话 Cookie 备份池:当 Cookie 更新时,旧 Cookie(具备约 30 天长效寿命)推入备份池,最多保留 maxBackups 份
*/
export function rotateBackupCookies(
existing?: { cookie?: string; backupCookies?: string[] },
newCookie?: string,
incomingBackups?: string[],
maxBackups = 5
): string[] {
const currentCookie = newCookie !== undefined ? newCookie : existing?.cookie;
const previousCookies = [
...(incomingBackups || []),
existing?.cookie,
...(existing?.backupCookies || [])
].filter((c): c is string => Boolean(c) && c !== currentCookie);
return Array.from(new Set(previousCookies)).slice(0, maxBackups);
}
/**
* 获取候选会话 Cookie 列表(主 Cookie 优先,随后依次尝试历史长效会话,用于断电超期兜底救险)
*/
export function resolveCandidateCookies(existing?: {
cookie?: string;
backupCookies?: string[];
}): string[] {
const list = [existing?.cookie, ...(existing?.backupCookies || [])].filter(
(c): c is string => Boolean(c)
);
return Array.from(new Set(list));
}
export type DelegationCreator = (
cookie: string | undefined
) => Promise<{ link: string; token: string }>;
/**
* 依次使用候选 Cookie 尝试创建新协助授权(实现断电停机超期后的长效 Session 兜底救险)
*/
export async function attemptCreateDelegationWithFallback(
candidateCookies: string[],
createFn: DelegationCreator
): Promise<{ link: string; token: string }> {
const cookiesToTry = candidateCookies.length > 0 ? candidateCookies : [undefined];
let lastError: unknown = null;
for (const cookie of cookiesToTry) {
try {
const res = await createFn(cookie);
if (res?.link && res?.token) {
return res;
}
} catch (err: unknown) {
lastError = err;
}
}
throw lastError || new Error("未能成功换发新协助授权链接");
}
+17
View File
@@ -7,8 +7,10 @@ import {
clearSealSession,
getCorpTokenCache,
getHoseAuthCache,
getSealDelegateAuthCache,
getSealSession,
setHoseAuthCache,
setSealDelegateAuthCache,
setSealSession
} from "./token-store.js";
import { SealSession } from "./types.js";
@@ -113,6 +115,21 @@ describe("token-store", () => {
expect(getCorpTokenCache("corp-hose")).toEqual({});
});
test("sets, retrieves, and updates seal delegate auth cache", () => {
makeTempStore();
const delegateCache = {
cookie: "__Secure-x-seal.session_token=initial-cookie",
backupCookies: ["backup-1", "backup-2"],
updatedAt: Date.now()
};
setSealDelegateAuthCache("corp-delegate", delegateCache);
expect(getSealDelegateAuthCache("corp-delegate")).toEqual(delegateCache);
clearCorpTokenCache("corp-delegate");
expect(getSealDelegateAuthCache("corp-delegate")).toEqual({});
});
test("falls back to reading legacy token store when primary does not exist", () => {
const legacyPath = makeTempStore(true);
const session: SealSession = {
+16
View File
@@ -5,6 +5,7 @@ import { SEAL_CONFIG_DIR } from "../paths.js";
import {
CorpTokenCache,
HoseAuthCache,
SealDelegateAuthCache,
SealSession,
TokenStore,
TokenStoreSchema
@@ -93,6 +94,21 @@ export function setHoseAuthCache(corpId: string, hose: HoseAuthCache): void {
});
}
export function getSealDelegateAuthCache(corpId: string): SealDelegateAuthCache {
return readStore()[corpId]?.sealDelegate ?? {};
}
export function setSealDelegateAuthCache(corpId: string, sealDelegate: SealDelegateAuthCache): void {
const store = readStore();
writeStore({
...store,
[corpId]: {
...store[corpId],
sealDelegate
}
});
}
export function clearCorpTokenCache(corpId: string): void {
const store = readStore();
delete store[corpId];
+9 -1
View File
@@ -28,9 +28,16 @@ export const HoseAuthCacheSchema = z.object({
closeapi: TokenEntrySchema.optional()
});
export const SealDelegateAuthCacheSchema = z.object({
cookie: z.string().optional(),
backupCookies: z.array(z.string()).optional(),
updatedAt: z.number().optional()
});
export const CorpTokenCacheSchema = z.object({
seal: SealSessionSchema.optional(),
hose: HoseAuthCacheSchema.optional()
hose: HoseAuthCacheSchema.optional(),
sealDelegate: SealDelegateAuthCacheSchema.optional()
});
export const TokenStoreSchema = z.record(z.string(), CorpTokenCacheSchema);
@@ -39,5 +46,6 @@ export type TokenEntry = z.infer<typeof TokenEntrySchema>;
export type SealEnterpriseConfig = z.infer<typeof SealEnterpriseConfigSchema>;
export type SealSession = z.infer<typeof SealSessionSchema>;
export type HoseAuthCache = z.infer<typeof HoseAuthCacheSchema>;
export type SealDelegateAuthCache = z.infer<typeof SealDelegateAuthCacheSchema>;
export type CorpTokenCache = z.infer<typeof CorpTokenCacheSchema>;
export type TokenStore = z.infer<typeof TokenStoreSchema>;
+7 -4
View File
@@ -25,8 +25,9 @@ import file21 from "../../skills/seal-use/references/langfuse-trace.md" with { t
import file22 from "../../skills/seal-use/references/report-templates.md" with { type: "text" };
import file23 from "../../skills/seal-use/references/rule-lightweight.md" with { type: "text" };
import file24 from "../../skills/seal-use/references/rule-lint.md" with { type: "text" };
import file25 from "../../skills/seal-use/references/staging-simulation-workflow.md" with { type: "text" };
import file26 from "../../skills/seal-use/references/webhook-resource-pack.md" with { type: "text" };
import file25 from "../../skills/seal-use/references/sealai-browser-rum.md" with { type: "text" };
import file26 from "../../skills/seal-use/references/staging-simulation-workflow.md" with { type: "text" };
import file27 from "../../skills/seal-use/references/webhook-resource-pack.md" with { type: "text" };
export const EMBEDDED_SKILL_TEXT_FILES: Record<string, string> = {
"SKILL.md": file0,
@@ -48,8 +49,9 @@ export const EMBEDDED_SKILL_TEXT_FILES: Record<string, string> = {
"references/report-templates.md": file22,
"references/rule-lightweight.md": file23,
"references/rule-lint.md": file24,
"references/staging-simulation-workflow.md": file25,
"references/webhook-resource-pack.md": file26,
"references/sealai-browser-rum.md": file25,
"references/staging-simulation-workflow.md": file26,
"references/webhook-resource-pack.md": file27,
};
export const EMBEDDED_SKILL_ASSET_PATHS: Record<string, string> = {
@@ -87,6 +89,7 @@ export const EMBEDDED_SKILL_ALL_PATHS = [
"references/report-templates.md",
"references/rule-lightweight.md",
"references/rule-lint.md",
"references/sealai-browser-rum.md",
"references/staging-simulation-workflow.md",
"references/webhook-resource-pack.md",
];
+1
View File
@@ -47,6 +47,7 @@ export async function onboardAssistanceLink(link: string, input: AssistanceLinkO
token: session.token,
sealUrl: session.sealUrl,
expiresIn: session.expiresIn,
sessionCookie: session.sessionCookie,
user: session.user,
tenant: session.tenant
}
+16
View File
@@ -15,6 +15,7 @@ import {
getInsightRisksByTag,
getInsightPerformance,
getApprovalRunRawJson,
exportApprovalRulesCsv,
analyzeInsightRecord,
listExpenses,
listInvoices,
@@ -41,6 +42,21 @@ describe("native approval JSON", () => {
});
});
describe("official approval rules CSV export", () => {
test("reads the server-generated CSV from the data envelope", async () => {
let requestedUrl = "";
const client = {
get: (url: string) => {
requestedUrl = url;
return { json: async () => ({ data: { csv: "code,description\r\n001,测试" } }) };
}
} as unknown as KyInstance;
await expect(exportApprovalRulesCsv(client)).resolves.toBe("code,description\r\n001,测试");
expect(requestedUrl).toBe("api/v1/rules/export/csv");
});
});
describe("Seal contact API", () => {
test("sends the contact search term as query", async () => {
let requestedUrl = "";
+6
View File
@@ -121,6 +121,12 @@ export async function listApprovalRules(client: KyInstance): Promise<ApprovalRul
return unwrap(await client.get("api/v1/rules"), ApprovalRulesDataSchema);
}
export async function exportApprovalRulesCsv(client: KyInstance): Promise<string> {
const response = await client.get("api/v1/rules/export/csv");
const result = await unwrap(response, z.object({ csv: z.string() }));
return result.csv;
}
export async function createApprovalRule(
client: KyInstance,
params: { description: string; scope: string; strictness: string }
+1
View File
@@ -60,6 +60,7 @@ export const SEAL_READ_ONLY_CAPABILITIES: ReadonlySet<string> = new Set([
"sealApprovalRuleVersionsList",
"sealApprovalRulesLint",
"sealApprovalRulesList",
"sealApprovalRulesExportCsv",
"sealApprovalRulesPull",
"sealApprovalRunAttachmentsGet",
"sealApprovalRunCitedRulesGet",
+13
View File
@@ -3,6 +3,7 @@ import type { KyInstance } from "ky";
import * as api from "../api.js";
import { createDocument, deleteDocument, documentCreateSchema, documentDeleteSchema, documentListSchema, documentUpdateSchema, listDocuments, updateDocument } from "../documents/service.js";
import { recodeRules, type RecodeOptions } from "../rules/recode.js";
import { exportOfficialRulesCsv } from "../rules/export-csv.js";
import { executeRulePush } from "../rules/push.js";
import { formatBeijingIso } from "../../../core/config/timestamps.js";
import { loadGlobalConfig } from "../../../core/config/loader.js";
@@ -719,6 +720,18 @@ export const rulesCapabilities = [
};
}
},
{
name: "sealApprovalRulesExportCsv",
description: "Call the official SealAI rules CSV export endpoint and save its CSV payload unchanged",
parameters: z.object({
out: z.string().optional().describe("Output file path; defaults to the Downloads directory")
}),
handler: async (
client: KyInstance,
params: { out?: string },
context: CapabilityContext
) => exportOfficialRulesCsv(client, context.corp, params.out)
},
{
name: "sealApprovalRulesPush",
description: "将本地规则文件增量同步到远端草稿;支持持久化步骤恢复记录、状态核对(--status)与直接发布正式版本",
+13
View File
@@ -8,6 +8,7 @@ import {
} from "../../../core/config/types.js";
import { createSealClientForUrl } from "../../../core/http/factory.js";
import { resolveSealCustomHeaders } from "../../../core/http/request-headers.js";
import { setSealDelegateAuthCache } from "../../../core/auth/token-store.js";
import { getMe } from "../api.js";
export type RemoteSealIdentity = {
@@ -39,6 +40,7 @@ export type SealDelegateSession = {
token: string;
sealUrl: string;
expiresIn: number;
sessionCookie?: string;
user: Record<string, unknown>;
tenant: Record<string, unknown>;
};
@@ -100,6 +102,17 @@ export function persistSealDelegateSession(input: {
remote: { user: input.session.user, tenant: input.session.tenant }
}
);
if (input.session.sessionCookie) {
try {
setSealDelegateAuthCache(saved.config.id, {
cookie: input.session.sessionCookie,
backupCookies: [],
updatedAt: Date.now()
});
} catch {
// ignore cache write error
}
}
return { ...saved, tenantId, tenantSlug };
}
+21 -1
View File
@@ -4,7 +4,7 @@ import { formatBeijingIso } from "../../../../core/config/timestamps.js";
import { validationError } from "../../../../core/errors.js";
import type { ApprovalRun } from "../../types.js";
import type { ReportDemand } from "./describe.js";
import { loadReviews, ReviewsMap, type ReviewRecord } from "./review-store.js";
import { loadReviews, recordDivergences, ReviewsMap, type ReviewRecord } from "./review-store.js";
/** 单据在决策空间里的极性:同意为正向、驳回/终止为反向,用于比对 AI 与人工是否同向。 */
type Polarity = "pass" | "reject" | "unknown";
@@ -307,6 +307,26 @@ export async function collectReportData(
data.blocks = blocks;
fetched.blocks = true;
const divergedBlocks = blocks.filter((b) => b.agreement === "diverged");
if (divergedBlocks.length > 0) {
try {
recordDivergences(
options.corp.id,
divergedBlocks.map((b) => ({
corpId: options.corp.id,
recordId: b.recordId ?? b.sn,
sn: b.sn,
docTitle: b.title,
aiDecision: b.aiDecision,
manualDecision: b.humanResult,
divergenceType: `${b.aiDecision || "未知"}_${b.humanResult || "未知"}`,
createdAt: b.createdAt ? new Date(b.createdAt).getTime() : undefined,
discoveredAt: Date.now()
}))
);
} catch {}
}
} catch {
// 分块拉取失败:章节保持模板原文
}
@@ -0,0 +1,173 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
closeReviewsDb,
countUnreviewedDivergences,
dismissDivergencePrompt,
isDivergenceDismissed,
listUnreviewedDivergences,
recordDivergences,
shouldPromptDivergence,
writeReview
} from "./review-store.js";
describe("review-divergence: 分歧待办与频控提醒机制", () => {
let testDir: string;
beforeEach(() => {
testDir = mkdtempSync(join(tmpdir(), "seal-reviews-divergence-test-"));
process.env.SEAL_USE_REVIEWS_STORE = join(testDir, "reviews.sqlite");
process.env.SEAL_USE_REVIEWS_DIR = join(testDir, "reviews");
});
afterEach(() => {
closeReviewsDb();
delete process.env.SEAL_USE_REVIEWS_STORE;
delete process.env.SEAL_USE_REVIEWS_DIR;
rmSync(testDir, { recursive: true, force: true });
});
test("录入分歧单据并能正确查询待整理数量", () => {
const corpId = "corp-huangfeng";
expect(countUnreviewedDivergences(corpId)).toBe(0);
recordDivergences(corpId, [
{
corpId,
recordId: "run-001",
sn: "SN-20261101-01",
docTitle: "差旅费报销单",
amount: "¥1,200",
aiDecision: "驳回",
manualDecision: "通过",
divergenceType: "AI驳回_人工通过",
discoveredAt: Date.now()
},
{
corpId,
recordId: "run-002",
sn: "SN-20261101-02",
docTitle: "办公用品采购",
amount: "¥4,500",
aiDecision: "通过",
manualDecision: "驳回",
divergenceType: "AI通过_人工驳回",
discoveredAt: Date.now()
}
]);
expect(countUnreviewedDivergences(corpId)).toBe(2);
const unreviewed = listUnreviewedDivergences(corpId);
expect(unreviewed).toHaveLength(2);
expect(unreviewed[0]!.sn).toBe("SN-20261101-01");
});
test("进行人工裁决打标后,待整理数量自动减少", () => {
const corpId = "corp-huangfeng";
recordDivergences(corpId, [
{
corpId,
recordId: "run-001",
sn: "SN-001",
discoveredAt: Date.now()
},
{
corpId,
recordId: "run-002",
sn: "SN-002",
discoveredAt: Date.now()
}
]);
expect(countUnreviewedDivergences(corpId)).toBe(2);
// 人工整理了 run-001
writeReview(corpId, {
recordId: "run-001",
sn: "SN-001",
verdict: "ai_correct",
note: "发票确实开错抬头,AI驳回正确"
});
expect(countUnreviewedDivergences(corpId)).toBe(1);
const remaining = listUnreviewedDivergences(corpId);
expect(remaining).toHaveLength(1);
expect(remaining[0]!.sn).toBe("SN-002");
});
test("shouldPromptDivergence 遵守时间频控,避免连续打扰", () => {
const corpId = "corp-huangfeng";
// 第一次允许提醒
expect(shouldPromptDivergence(corpId, 10_000)).toBe(true);
// 立即再次检查,在 10s 内被频控拦截
expect(shouldPromptDivergence(corpId, 10_000)).toBe(false);
// 另一个企业不受影响
expect(shouldPromptDivergence("corp-other", 10_000)).toBe(true);
});
test("dismissDivergencePrompt 在用户拒绝时进入静音抑制期,绝不重复打扰", () => {
const corpId = "corp-huangfeng";
expect(isDivergenceDismissed(corpId)).toBe(false);
// 用户说“今天不想审批/别烦我”,Agent 调用 dismiss 24小时
dismissDivergencePrompt(corpId, 24);
expect(isDivergenceDismissed(corpId)).toBe(true);
// 在静音期内,无论频控如何都不再提醒
expect(shouldPromptDivergence(corpId, 0)).toBe(false);
});
test("自动过滤超过 30 天的陈年旧单,只提示近 30 天的分歧单据", () => {
const corpId = "corp-huangfeng";
const now = Date.now();
const eightyDaysAgo = now - 80 * 24 * 3600 * 1000;
recordDivergences(corpId, [
{
corpId,
recordId: "run-old-march",
sn: "SN-20260315-01",
docTitle: "3月份招待费",
createdAt: eightyDaysAgo,
discoveredAt: eightyDaysAgo
},
{
corpId,
recordId: "run-recent-today",
sn: "SN-20261102-01",
docTitle: "今天差旅费",
createdAt: now,
discoveredAt: now
}
]);
// 默认只统计近 30 天:3月份的陈年旧账自动排除,不打扰当前月份
expect(countUnreviewedDivergences(corpId)).toBe(1);
const recent = listUnreviewedDivergences(corpId);
expect(recent).toHaveLength(1);
expect(recent[0]!.sn).toBe("SN-20261102-01");
// 若显式传入 0 (或 --all),仍可检索历史全量
expect(countUnreviewedDivergences(corpId, 0)).toBe(2);
const all = listUnreviewedDivergences(corpId, 50, 0);
expect(all).toHaveLength(2);
});
test("滑动窗口频控:同一个企业 5 小时内最多主动提醒 1 次", () => {
const corpId = "corp-sliding-window";
const fiveHoursMs = 5 * 60 * 60 * 1000;
// 第 1 次:允许提醒
expect(shouldPromptDivergence(corpId, fiveHoursMs)).toBe(true);
// 5 小时以内再次触发:拦截
expect(shouldPromptDivergence(corpId, fiveHoursMs)).toBe(false);
// 传入 0 间隔(即超过 5 小时后):再次允许提醒
expect(shouldPromptDivergence(corpId, 0)).toBe(true);
});
});
+467 -34
View File
@@ -1,19 +1,19 @@
import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync } from "node:fs";
import { Database } from "bun:sqlite";
import { appendFileSync, chmodSync, existsSync, mkdirSync, readFileSync, readdirSync } from "node:fs";
import { dirname, join } from "node:path";
import { validationError } from "../../../../core/errors.js";
import { SEAL_STATE_DIR } from "../../../../core/paths.js";
/**
* 人工裁决的本地持久化(JSONL,按租户分片,支持 recordId 与 SN 双键检索)。
* 人工裁决与分歧待办的本地存储(统一放置在 ~/.config/seal-use/state/)
*
* 为什么是 JSONL:跨周期 review 天然是追加写入场景——每审一批写一批,不整文件重写,
* 避免并发覆盖;单行一条记录,可直接 tail/grep/手改,也可被 CLI 批量导入。
* 为什么按租户分片:租户天然数据隔离。
* 标识符规则:优先以具体审核运行 ID(recordId)精确定位单次审核;同时支持单据 SN 作为业务自然键。
* 后写覆盖先写。
* 存储模型:
* 1. 主存储:~/.config/seal-use/state/reviews.sqlite,支持秒级索引与差集运算(支撑日常命令在 stderr 温和提示);
* 2. 伴生与导出存储:~/.config/seal-use/state/reviews/<corpId>[-<scope>].jsonl,作为人类可读与批量台账交互的冷备份;
* 3. 为什么是 State 而不是 Cache:人工裁决是用户不可逆的智力决策(谁对谁错、特批备注),不上传云端,属于单机核心资产,
* 防止随 ~/.cache 一键清理而丢失。
*/
/** 人工裁决结论:谁对。both_* 覆盖"一致但仍复核"与"分歧后判定双方各有对错"的场景。 */
export type ReviewVerdict =
| "ai_correct" // AI 对,人工错
| "human_correct" // 人工对,AI 错
@@ -22,21 +22,29 @@ export type ReviewVerdict =
| "undecided"; // 已 review 但暂无法判定(保留占位,后续可改判)
export type ReviewRecord = {
/** 审核运行记录 ID(精确裁决键) */
recordId?: string;
/** 合思/源单据 SN(业务自然键) */
sn?: string;
/** 裁决所属统计周期或月份(可选留痕) */
month?: string;
scope?: string;
verdict: ReviewVerdict;
/** 裁决人(可选,留痕用) */
reviewedBy?: string;
/** 裁决备注(可选):为什么这么判 */
note?: string;
/** 写入时间(北京时间 ISO 秒) */
recordedAt: string;
};
export type DivergenceItem = {
corpId: string;
recordId: string;
sn: string;
docTitle?: string;
amount?: string;
aiDecision?: string;
manualDecision?: string;
divergenceType?: string;
createdAt?: number;
discoveredAt: number;
};
const VERDICTS: ReadonlySet<string> = new Set([
"ai_correct",
"human_correct",
@@ -97,20 +105,27 @@ export class ReviewsMap {
}
const REVIEWS_DIR_ENV = "SEAL_USE_REVIEWS_DIR";
const REVIEWS_STORE_ENV = "SEAL_USE_REVIEWS_STORE";
/** 裁决存储根目录:~/.config/seal-use/state/reviews/。可用 SEAL_USE_REVIEWS_DIR 覆盖(测试/隔离)。 */
export function reviewsDir(): string {
const configured = process.env[REVIEWS_DIR_ENV]?.trim();
if (configured) return configured;
return join(SEAL_STATE_DIR, "reviews");
}
/** 分片路径:<reviewsDir>/<corpId>[-<scope>].jsonl */
export function reviewFilePath(corpId: string, scope?: string): string {
const cleanCorp = sanitizeCorpId(corpId);
return scope ? join(reviewsDir(), `${cleanCorp}-${scope}.jsonl`) : join(reviewsDir(), `${cleanCorp}.jsonl`);
}
export function getReviewStorePath(): string {
const configured = process.env[REVIEWS_STORE_ENV]?.trim();
if (configured) return configured;
const legacyDir = process.env[REVIEWS_DIR_ENV]?.trim();
if (legacyDir) return join(legacyDir, "reviews.sqlite");
return join(SEAL_STATE_DIR, "reviews.sqlite");
}
function sanitizeCorpId(corpId: string): string {
return corpId.replace(/[^a-zA-Z0-9._-]/g, "_");
}
@@ -123,21 +138,109 @@ function assertVerdict(verdict: string): asserts verdict is ReviewVerdict {
}
}
let dbInstance: Database | null = null;
let currentDbPath: string | null = null;
export function openReviewsDb(path = getReviewStorePath()): Database {
if (dbInstance && currentDbPath === path) {
return dbInstance;
}
if (dbInstance) {
try {
dbInstance.close();
} catch {}
dbInstance = null;
}
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
const db = new Database(path, { create: true });
try {
chmodSync(path, 0o600);
db.exec("PRAGMA busy_timeout = 5000");
db.exec(`
CREATE TABLE IF NOT EXISTS reviews (
id INTEGER PRIMARY KEY AUTOINCREMENT,
corp_id TEXT NOT NULL,
record_id TEXT,
sn TEXT,
month TEXT,
scope TEXT,
verdict TEXT NOT NULL,
reviewed_by TEXT,
note TEXT,
recorded_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_reviews_lookup ON reviews (corp_id, record_id, sn);
CREATE INDEX IF NOT EXISTS idx_reviews_scope ON reviews (corp_id, scope);
CREATE INDEX IF NOT EXISTS idx_reviews_month ON reviews (corp_id, month);
CREATE TABLE IF NOT EXISTS divergences (
corp_id TEXT NOT NULL,
record_id TEXT NOT NULL,
sn TEXT NOT NULL,
doc_title TEXT,
amount TEXT,
ai_decision TEXT,
manual_decision TEXT,
divergence_type TEXT,
created_at INTEGER,
discovered_at INTEGER NOT NULL,
PRIMARY KEY (corp_id, record_id)
);
CREATE INDEX IF NOT EXISTS idx_divergences_corp ON divergences (corp_id, sn);
CREATE TABLE IF NOT EXISTS prompt_throttle (
corp_id TEXT PRIMARY KEY,
last_prompt_date TEXT,
prompt_count INTEGER NOT NULL DEFAULT 1,
last_prompted_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS review_dismissals (
corp_id TEXT PRIMARY KEY,
dismissed_until INTEGER NOT NULL
);
`);
try {
db.exec("ALTER TABLE prompt_throttle ADD COLUMN last_prompt_date TEXT");
} catch {}
try {
db.exec("ALTER TABLE prompt_throttle ADD COLUMN prompt_count INTEGER DEFAULT 1");
} catch {}
dbInstance = db;
currentDbPath = path;
return db;
} catch (error) {
db.close();
throw error;
}
}
export function closeReviewsDb(): void {
if (dbInstance) {
try {
dbInstance.close();
} catch {}
dbInstance = null;
currentDbPath = null;
}
}
/**
* 读取某租户的全部裁决。若指定 scope(如月份),则仅读取该分片;否则读取该租户的主文件与各分片文件。按后写覆盖先写。
* 历史 JSONL 自动平滑迁移或同步到 SQLite
*/
export function loadReviews(corpId: string, scope?: string): ReviewsMap {
const reviews = new ReviewsMap();
function syncLegacyJsonlIfPresent(corpId: string, db: Database, targetScope?: string): void {
const targetDir = reviewsDir();
if (!existsSync(targetDir)) return;
const sanitized = sanitizeCorpId(corpId);
const targetDir = reviewsDir();
if (!existsSync(targetDir)) return reviews;
const targetFile = reviewFilePath(corpId, scope);
const filesToRead: string[] = [];
if (scope) {
if (existsSync(targetFile)) filesToRead.push(targetFile);
if (targetScope) {
const scopeFile = reviewFilePath(corpId, targetScope);
if (existsSync(scopeFile)) filesToRead.push(scopeFile);
} else {
if (existsSync(targetFile)) filesToRead.push(targetFile);
const primary = reviewFilePath(corpId);
if (existsSync(primary)) filesToRead.push(primary);
try {
const allFiles = readdirSync(targetDir);
for (const f of allFiles) {
@@ -148,7 +251,20 @@ export function loadReviews(corpId: string, scope?: string): ReviewsMap {
} catch {}
}
for (const filePath of filesToRead) {
const insertStmt = db.prepare(`
INSERT INTO reviews (corp_id, record_id, sn, month, scope, verdict, reviewed_by, note, recorded_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
`);
const checkStmt = db.prepare(`
SELECT id FROM reviews
WHERE corp_id = ? AND (
(record_id IS NOT NULL AND record_id = ?) OR
(sn IS NOT NULL AND sn = ?)
) AND recorded_at = ? LIMIT 1
`);
for (const filePath of new Set(filesToRead)) {
try {
const lines = readFileSync(filePath, "utf8").split("\n");
for (const line of lines) {
@@ -157,18 +273,87 @@ export function loadReviews(corpId: string, scope?: string): ReviewsMap {
try {
const parsed = JSON.parse(trimmed) as ReviewRecord;
if (parsed && (parsed.recordId || parsed.sn) && VERDICTS.has(parsed.verdict)) {
reviews.set(parsed.recordId ?? parsed.sn!, parsed);
const exists = checkStmt.get(
corpId,
parsed.recordId ?? null,
parsed.sn ?? null,
parsed.recordedAt
);
if (!exists) {
insertStmt.run(
corpId,
parsed.recordId ?? null,
parsed.sn ?? null,
parsed.month ?? null,
parsed.scope ?? parsed.month ?? null,
parsed.verdict,
parsed.reviewedBy ?? null,
parsed.note ?? null,
parsed.recordedAt
);
}
}
} catch {}
} catch {
// 跳过损坏行
}
}
} catch {}
}
}
/**
* 读取某租户的全部裁决。若指定 scope(如月份),则仅读取该分片。按后写覆盖先写。
*/
export function loadReviews(corpId: string, scope?: string): ReviewsMap {
const reviews = new ReviewsMap();
const db = openReviewsDb();
syncLegacyJsonlIfPresent(corpId, db, scope);
let query = `
SELECT record_id, sn, month, scope, verdict, reviewed_by, note, recorded_at
FROM reviews
WHERE corp_id = ?
`;
const params: string[] = [corpId];
if (scope) {
query += " AND (scope = ? OR month = ?)";
params.push(scope, scope);
}
query += " ORDER BY id ASC";
const rows = db.prepare(query).all(...params) as Array<{
record_id: string | null;
sn: string | null;
month: string | null;
scope: string | null;
verdict: string;
reviewed_by: string | null;
note: string | null;
recorded_at: string;
}>;
for (const row of rows) {
if (VERDICTS.has(row.verdict)) {
const record: ReviewRecord = {
recordId: row.record_id || undefined,
sn: row.sn || undefined,
month: row.month || undefined,
scope: row.scope || undefined,
verdict: row.verdict as ReviewVerdict,
reviewedBy: row.reviewed_by || undefined,
note: row.note || undefined,
recordedAt: row.recorded_at
};
reviews.set(record.recordId ?? record.sn!, record);
}
}
return reviews;
}
/**
* 追加写一条裁决到磁盘(支持 recordId 与 sn)。
* 记录一条裁决到 SQLite 存储,同时双写到伴生 JSONL 文件
*/
export function writeReview(
corpId: string,
@@ -193,19 +378,267 @@ export function writeReview(
}
assertVerdict(input.verdict);
const recordedAt =
input.recordedAt ?? new Date().toISOString().slice(0, 19).replace("T", " ");
const scope = input.scope ?? input.month;
const db = openReviewsDb();
const stmt = db.prepare(`
INSERT INTO reviews (corp_id, record_id, sn, month, scope, verdict, reviewed_by, note, recorded_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
`);
stmt.run(
corpId,
recordId ?? null,
sn ?? null,
input.month ?? null,
scope ?? null,
input.verdict,
input.reviewedBy?.trim() ?? null,
input.note?.trim() ?? null,
recordedAt
);
const record: ReviewRecord = {
...(recordId ? { recordId } : {}),
...(sn ? { sn } : {}),
...(input.month ? { month: input.month } : {}),
...(scope ? { scope } : {}),
verdict: input.verdict,
...(input.reviewedBy?.trim() ? { reviewedBy: input.reviewedBy.trim() } : {}),
...(input.note?.trim() ? { note: input.note.trim() } : {}),
recordedAt: input.recordedAt ?? new Date().toISOString().slice(0, 19).replace("T", " ")
recordedAt
};
const scope = input.scope ?? input.month;
const filePath = reviewFilePath(corpId, scope);
mkdirSync(dirname(filePath), { recursive: true, mode: 0o700 });
appendFileSync(filePath, JSON.stringify(record) + "\n", { encoding: "utf-8", mode: 0o600 });
// 双写到伴生 JSONL(明文冷备与纯文本兼容)
try {
const filePath = reviewFilePath(corpId, scope);
mkdirSync(dirname(filePath), { recursive: true, mode: 0o700 });
appendFileSync(filePath, JSON.stringify(record) + "\n", { encoding: "utf-8", mode: 0o600 });
} catch {}
return record;
}
/**
* 批量同步/保存分歧单据到底层 SQLite
*/
export function recordDivergences(corpId: string, items: DivergenceItem[]): number {
if (items.length === 0) return 0;
const db = openReviewsDb();
const stmt = db.prepare(`
INSERT INTO divergences (corp_id, record_id, sn, doc_title, amount, ai_decision, manual_decision, divergence_type, created_at, discovered_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(corp_id, record_id) DO UPDATE SET
sn = excluded.sn,
doc_title = coalesce(excluded.doc_title, divergences.doc_title),
amount = coalesce(excluded.amount, divergences.amount),
ai_decision = coalesce(excluded.ai_decision, divergences.ai_decision),
manual_decision = coalesce(excluded.manual_decision, divergences.manual_decision),
divergence_type = coalesce(excluded.divergence_type, divergences.divergence_type)
`);
let count = 0;
db.transaction(() => {
for (const item of items) {
stmt.run(
corpId,
item.recordId,
item.sn,
item.docTitle ?? null,
item.amount ?? null,
item.aiDecision ?? null,
item.manualDecision ?? null,
item.divergenceType ?? null,
item.createdAt ?? null,
item.discoveredAt || Date.now()
);
count++;
}
})();
return count;
}
export const DEFAULT_RECENCY_DAYS = 30;
function getLocalDateString(): string {
const d = new Date();
const year = d.getFullYear();
const month = String(d.getMonth() + 1).padStart(2, "0");
const day = String(d.getDate()).padStart(2, "0");
return `${year}-${month}-${day}`;
}
/**
* 列出某企业未完成人工复核的分歧单据(用于少量多次整理)
* 默认只检索近 30 天内发生的单据,避免数月前的陈年旧账打扰日常体验
*/
export function listUnreviewedDivergences(
corpId: string,
limit = 50,
maxAgeDays = DEFAULT_RECENCY_DAYS
): DivergenceItem[] {
const db = openReviewsDb();
syncLegacyJsonlIfPresent(corpId, db);
let query = `
SELECT d.corp_id, d.record_id, d.sn, d.doc_title, d.amount, d.ai_decision, d.manual_decision, d.divergence_type, d.created_at, d.discovered_at
FROM divergences d
LEFT JOIN reviews r ON r.corp_id = d.corp_id AND (
(r.record_id IS NOT NULL AND r.record_id = d.record_id) OR
(r.sn IS NOT NULL AND r.sn = d.sn)
)
WHERE d.corp_id = ? AND r.id IS NULL
`;
const params: (string | number)[] = [corpId];
if (maxAgeDays > 0) {
const cutoff = Date.now() - maxAgeDays * 24 * 3600 * 1000;
query += ` AND COALESCE(d.created_at, d.discovered_at) >= ?`;
params.push(cutoff);
}
query += `
ORDER BY d.created_at DESC, d.discovered_at DESC
LIMIT ?
`;
params.push(limit);
const rows = db.prepare(query).all(...params) as Array<{
corp_id: string;
record_id: string;
sn: string;
doc_title: string | null;
amount: string | null;
ai_decision: string | null;
manual_decision: string | null;
divergence_type: string | null;
created_at: number | null;
discovered_at: number;
}>;
return rows.map((r) => ({
corpId: r.corp_id,
recordId: r.record_id,
sn: r.sn,
docTitle: r.doc_title || undefined,
amount: r.amount || undefined,
aiDecision: r.ai_decision || undefined,
manualDecision: r.manual_decision || undefined,
divergenceType: r.divergence_type || undefined,
createdAt: r.created_at || undefined,
discoveredAt: r.discovered_at
}));
}
/**
* 统计某企业待整理分歧单据数量(耗时 < 0.2ms,供日常命令快速探测)
* 默认只统计近 30 天内产生的分歧,陈年单据自动归入离线历史池,零打扰
*/
export function countUnreviewedDivergences(
corpId: string,
maxAgeDays = DEFAULT_RECENCY_DAYS
): number {
try {
const db = openReviewsDb();
syncLegacyJsonlIfPresent(corpId, db);
let query = `
SELECT COUNT(*) as count
FROM divergences d
LEFT JOIN reviews r ON r.corp_id = d.corp_id AND (
(r.record_id IS NOT NULL AND r.record_id = d.record_id) OR
(r.sn IS NOT NULL AND r.sn = d.sn)
)
WHERE d.corp_id = ? AND r.id IS NULL
`;
const params: (string | number)[] = [corpId];
if (maxAgeDays > 0) {
const cutoff = Date.now() - maxAgeDays * 24 * 3600 * 1000;
query += ` AND COALESCE(d.created_at, d.discovered_at) >= ?`;
params.push(cutoff);
}
const row = db.prepare(query).get(...params) as { count: number } | undefined;
return row?.count ?? 0;
} catch {
return 0;
}
}
/**
* 抑制该企业的提示(当用户表示当天不想处理时,Agent 调用此函数静音)
*/
export function dismissDivergencePrompt(corpId: string, hours = 24): number {
try {
const db = openReviewsDb();
const until = Date.now() + Math.max(1, hours) * 3600 * 1000;
db.prepare(`
INSERT INTO review_dismissals (corp_id, dismissed_until)
VALUES (?, ?)
ON CONFLICT(corp_id) DO UPDATE SET dismissed_until = excluded.dismissed_until
`).run(corpId, until);
return until;
} catch {
return Date.now();
}
}
/**
* 检查该企业是否处于人工拒绝的静音抑制期内
*/
export function isDivergenceDismissed(corpId: string): boolean {
try {
const db = openReviewsDb();
const row = db
.prepare("SELECT dismissed_until FROM review_dismissals WHERE corp_id = ?")
.get(corpId) as { dismissed_until: number } | undefined;
return Boolean(row && row.dismissed_until > Date.now());
} catch {
return false;
}
}
export const DEFAULT_PROMPT_INTERVAL_MS = 5 * 60 * 60 * 1000; // 动态 5 小时滑动窗口
/**
* 频控检查(动态 5 小时滑动窗口与 24 小时人工封禁):
* 1. 显式静音优先:若企业处于 dismiss 抑制期内(默认 24 小时),直接返回 false;
* 2. 动态滑动窗口:同一个企业默认 5 小时内最多提醒 1 次(5 小时内提醒过则不再提醒);
* 3. 满足条件时记录当前时间戳并返回 true。
*/
export function shouldPromptDivergence(
corpId: string,
intervalMs = DEFAULT_PROMPT_INTERVAL_MS
): boolean {
try {
if (isDivergenceDismissed(corpId)) {
return false;
}
const db = openReviewsDb();
const now = Date.now();
const row = db
.prepare("SELECT last_prompted_at FROM prompt_throttle WHERE corp_id = ?")
.get(corpId) as { last_prompted_at?: number } | undefined;
if (row?.last_prompted_at && now - row.last_prompted_at < intervalMs) {
return false;
}
db.prepare(`
INSERT INTO prompt_throttle (corp_id, last_prompt_date, prompt_count, last_prompted_at)
VALUES (?, ?, ?, ?)
ON CONFLICT(corp_id) DO UPDATE SET
last_prompt_date = excluded.last_prompt_date,
prompt_count = excluded.prompt_count,
last_prompted_at = excluded.last_prompted_at
`).run(corpId, getLocalDateString(), 1, now);
return true;
} catch {
return false;
}
}
+42
View File
@@ -0,0 +1,42 @@
import { homedir } from "node:os";
import { join, resolve } from "node:path";
import type { KyInstance } from "ky";
import { formatBeijingIso } from "../../../core/config/timestamps.js";
import type { CorpConfig } from "../../../core/config/types.js";
import { writeSecureFile } from "../../../core/secure-file.js";
import * as api from "../api.js";
import { sanitizeFileName } from "../approval-runs/attachments.js";
export interface OfficialRulesCsvExportResult {
filePath: string;
corpName: string;
byteLength: number;
exportedAt: string;
source: "sealai-official-csv-endpoint";
}
export async function exportOfficialRulesCsv(
client: KyInstance,
corp: CorpConfig,
outputFile?: string
): Promise<OfficialRulesCsvExportResult> {
const exportedAt = formatBeijingIso();
const stamp = exportedAt.slice(0, 19).replace(/[-:T]/g, "");
const safeCorpName = sanitizeFileName(corp.name || corp.id);
const filePath = resolve(
outputFile ?? join(homedir(), "Downloads", `${safeCorpName}_审核规则官方导出_${stamp}.csv`)
);
const csv = await api.exportApprovalRulesCsv(client);
// The API response is a JSON envelope containing the server-generated CSV string.
// Persist that string as UTF-8 without parsing, reordering, normalizing, or rewriting CSV rows.
writeSecureFile(filePath, csv);
return {
filePath,
corpName: corp.name || corp.id,
byteLength: Buffer.byteLength(csv, "utf8"),
exportedAt,
source: "sealai-official-csv-endpoint"
};
}