feat: 原生 Seal 授权续期自愈与本地 SQLite 分歧待办闭环

- 授权自愈: 引入长效会话 Cookie 备份池,支持 Seal 原生协助授权到期与 401 报错时平滑自动换发与静默续期;
- 存储升级: 审核报告人工裁决底座迁移至 SQLite (~/.config/seal-use/state/reviews.sqlite),支持历史 JSONL 自动平滑导入与向后兼容双写;
- 分歧待办: 新增 report review unreviewed 与 dismiss 命令,收集人机不一致单据并在日常企业命令完成后于 stderr 注入 Agent 动作指引;
- 精密频控: 实现 30 天单据时效窗口过滤(陈年单据自动归档)、动态 5 小时滑动窗口频控与 24 小时人工拒审静音抑制协议;
- 透明认知: 全面补充 Skill 路由与帮助手册,消除黑盒,透传数据边界与安全红线。
This commit is contained in:
gitea committed 2026-11-02 15:22:47 +08:00
1 parent 5c46c9bcc4
commit 8c9f102931
21 files changed
+1668 -50

No files matched your search

+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.`);
+23 -1
View File
@@ -766,7 +766,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",
+2 -2
View File
@@ -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;
}